reactjs - React-sortable-hoc ReactJS库排序问题

标签 reactjs sorting npm

我正在尝试使用react-sortable-hoc 的示例。可排序无法保持排序状态。看看 GIF。

enter image description here

下面是我的示例代码..

import React, {Component} from 'react';
import {SortableContainer, SortableElement, arrayMove} from 'react-sortable-
hoc';
// Css
import './object_library.css'

const SortableItem = SortableElement(({value}) =>
<div className="Showcase_test_horizontalItem" >
    <div>{value}</div>
    <br />
    <TestSortable />
</div>
);

const SortableList = SortableContainer(({items}) => {
return (
    <div>
        {items.map((value, index) => (
            <SortableItem key={`item-${index}`} index={index} value={value} 
/>
        ))}
    </div>
  );
});

class TestSortable extends Component {
constructor(props) {
    super(props);
    this.state = {
        sum: 0
    }
    this.onAddChild = this.onAddChild.bind(this)
}
onAddChild () {
    let prevSum = this.state.sum + 1;
    this.setState({
        sum: prevSum
    });
}
render() {
    return (
        <div>
            <div> {this.state.sum} </div>
            <button className="my_plus_buttons" onClick={this.onAddChild}>+
            </button>
        </div>
    );
   }
 }

 class SortableComponent extends Component {
 state = {
    items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'],
 };
 onSortEnd = ({oldIndex, newIndex}) => {
    this.setState({
        items: arrayMove(this.state.items, oldIndex, newIndex),
    });
};
render() {
    return <SortableList items={this.state.items} onSortEnd={this.onSortEnd} 
    axis="x"/>;
  }
 }

 export default SortableComponent;

不确定为什么这个库不维护状态?

谢谢

最佳答案

在您的 SortableList 中,您根据当前索引设置一个键,这是正常的事情,但它似乎是导致问题的原因。让键与值匹配,它似乎按预期工作。

我猜 key 需要与底层组件一起移动。

const SortableList = SortableContainer(({ items }) => {
  return (
    <div>
      {items.map((value, index) => (
        <SortableItem key={`item-${value}`} index={index} value={value} />
      ))}
    </div>
  );
});

关于reactjs - React-sortable-hoc ReactJS库排序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44974598/

相关文章:

jquery - 未使用 jquery val() 方法调用 React 事件处理程序

Azure Artifacts 对于某些公共(public) npm 包返回 404

javascript - 域感知 React 路由器

javascript - 如何在 react 中使用 getAttribute?

javascript - 如何构建自定义material-ui组件

javascript - 如何对 rxjs 中的现有流进行排序?

用于替代字符串排序的 Java 比较器

php - 如何在每次迭代中以从上到下的方式旋转数组元素

javascript - 我今天如何在 package.json 中将 "exports"用于嵌套子模块和 typescript

node.js - `npm install` 不工作。未处理的拒绝错误: EISDIR: illegal operation on a directory