【问题标题】:react-sortable-hoc -- maintain new sort order without experimental class propertiesreact-sortable-hoc -- 在没有实验类属性的情况下保持新的排序顺序
【发布时间】:2019-03-09 20:03:45
【问题描述】:

以下配置未引发任何错误,但未维护新的排序顺序。拖动和关联的动画效果很好,但排序顺序本身永远不会永久改变。

我根据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} />;
    }
}

【问题讨论】:

    标签: reactjs react-sortable-hoc


    【解决方案1】:

    问题出在 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)

    请注意函数签名和您的实现的区别,oldIndexnewIndex 是通过对第一个参数使用对象解构来分配的。通过使用函数的第二个参数为oldIndex,它实际上将e作为值,在更新数组的顺序时显然不能用作索引!

    【讨论】:

    • 非常好——我也通过执行 `onSortEnd(args) { let oldIndex = args.oldIndex;让 newIndex = args.newIndex;`
    猜你喜欢
    • 2014-09-09
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 2012-10-15
    • 2011-08-03
    • 2021-08-28
    相关资源
    最近更新 更多