下面的配置没有抛出任何错误,但是没有维护新的排序顺序。拖动和关联动画运行良好,但排序顺序本身不会永久更改。
我对https://www.npmjs.com/package/react-sortable-hoc上的示例略微修改了代码。(我将一些代码移入构造函数中,以避免与实验类属性相关的错误。)
有什么想法吗?
import {
SortableContainer,
SortableElement,
arrayMove,
} from 'react-sortable-hoc';
const SortableItem = SortableElement(({value}) => <li>{value}</li>);
const SortableList = SortableContainer(({items}) => {
return (
<ul>
{items.map((value, index) => (
<SortableItem key={`item-${index}`} index={index} value={value} />
))}
</ul>
);
});
class SortableComponent extends Component {
constructor(props) {
super(props);
this.state = {};
this.state.items = [
"Gold",
"Crimson",
"Hotpink",
"Blueviolet",
"Cornflowerblue",
"Skyblue",
"Lightblue",
"Aquamarine",
"Burlywood"
];
this.onSortEnd = this.onSortEnd.bind(this);
}
onSortEnd(oldIndex, newIndex) {
this.setState(({items}) => ({
items: arrayMove(items, oldIndex, newIndex),
}));
}
render() {
return <SortableList items={this.state.items} onSortEnd={this.onSortEnd} />;
}
}发布于 2019-03-10 04:32:58
问题出在onSortEnd回调中:
onSortEnd(oldIndex, newIndex) {
this.setState(({items}) => ({
items: arrayMove(items, oldIndex, newIndex),
}));
}您需要将函数(oldIndex, newIndex)的参数更改为({ oldIndex, newIndex })
来自github文档(https://github.com/clauderic/react-sortable-hoc):onSortEnd -排序结束时调用的回调。function({oldIndex, newIndex, collection}, e)
注意函数签名和实现的不同,oldIndex和newIndex是通过在第一个参数上使用对象解构来赋值的。通过使用函数的第二个参数作为oldIndex,它实际上将e作为值,这显然不能在更新数组顺序时用作索引!
https://stackoverflow.com/questions/55081437
复制相似问题