sortTableComponent.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import React, { Component } from 'react';
  2. import { SortableContainer, SortableElement } from 'react-sortable-hoc';
  3. import { arrayMoveImmutable } from 'array-move';
  4. import { Card, Button } from 'antd';
  5. import { ImgGood } from '.';
  6. const SortableItem = SortableElement(({ value: { _id, url, onSave } }) =>
  7. <li className='liSortTable'>
  8. <Card>
  9. <ImgGood url={url} />
  10. <Button onClick={onSave}>Сохранить</Button>
  11. </Card>
  12. </li>);
  13. const SortableList = SortableContainer(({ items, idGood, onSave, onChangeImagesOnSer }) => {
  14. return (
  15. <>
  16. <ul className='sortTablelist' >
  17. {items.map((value, index) => (
  18. <SortableItem key={`item-${index}`} index={index} value={
  19. {
  20. _id: value._id,
  21. url: value.url,
  22. onSave: () => onSave(value._id)
  23. }
  24. } />
  25. ))}
  26. </ul>
  27. <Button type="primary" block onClick={onChangeImagesOnSer}>Сохранить на сервере</Button>
  28. </>
  29. );
  30. });
  31. class SortableComponent extends Component {
  32. state = {
  33. items: this.props.images,
  34. idGood: this.props.idGood,
  35. clearUpLoad: this.props.clearUpLoad
  36. };
  37. getState =() => console.log('this.state', this.state)
  38. onSortEnd = ({ oldIndex, newIndex }) => {
  39. this.setState(({ items }) => ({
  40. items: arrayMoveImmutable(items, oldIndex, newIndex)
  41. }));
  42. this.getState();
  43. };
  44. onChangeImagesOnSer = () => {
  45. const arrImagesForSave = this.state.items.map((item) => ({ _id: item._id }));
  46. this.props.onChangeArrInGood(this.state.idGood, arrImagesForSave);
  47. }
  48. onSave = (idImg) => {
  49. const newArrImgs = this.state.items.map((item) => {
  50. if (idImg === item._id) {
  51. return {
  52. _id: this.props.upLoad._id,
  53. url: this.props.upLoad.url
  54. };
  55. };
  56. return item;
  57. });
  58. this.setState(() => ({ items: newArrImgs }));
  59. this.state.clearUpLoad();
  60. }
  61. render () {
  62. return (
  63. <SortableList
  64. axis="xy"
  65. items={this.state.items}
  66. idGood={this.state.idGood}
  67. onSortEnd={this.onSortEnd}
  68. onSave={this.onSave}
  69. onChangeImagesOnSer={this.onChangeImagesOnSer}
  70. />);
  71. }
  72. }
  73. export default SortableComponent;