reactjs - react-sortable-hoc -- 在没有实验类属性的情况下保持新的排序顺序
问题描述
以下配置未引发任何错误,但未维护新的排序顺序。拖动和关联的动画效果很好,但排序顺序本身永远不会改变。
我已经从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} />;
}
}
解决方案
问题出在 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
作为值,在更新数组的顺序时显然不能用作索引!
推荐阅读
- javascript - React - 控制台警告和错误
- javascript - 当另一个类显示设置为 inline-block 时隐藏一个类!重要
- java - java.lang.NoClassDefFoundError:创建订单号错误;
- floating-point - 为什么非正规浮点值的处理速度较慢?
- javascript - 在 Jquery 页面重定向上预填充 Django 表单
- android - com.google.firebase.database.DatabaseException:无法在显示列表视图中将 java.util.HashMap 类型的值转换为字符串
- javascript - 如何在 ace-editor 中执行用户的代码
- python - 计算熊猫数据框中一列的 6 小时平均值,将值绘制为图形上的文本
- r - 如何通过取 R 中的两列来填充 NA?
- sql-server - 我可以将相关表添加到 PowerApps Canvas 应用程序吗?