首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >react-sortable-hoc --在没有实验类属性的情况下维护新的排序顺序

react-sortable-hoc --在没有实验类属性的情况下维护新的排序顺序
EN

Stack Overflow用户
提问于 2019-03-10 04:03:46
回答 1查看 1.7K关注 0票数 2

下面的配置没有抛出任何错误,但是没有维护新的排序顺序。拖动和关联动画运行良好,但排序顺序本身不会永久更改。

我对https://www.npmjs.com/package/react-sortable-hoc上的示例略微修改了代码。(我将一些代码移入构造函数中,以避免与实验类属性相关的错误。)

有什么想法吗?

代码语言:javascript
复制
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} />;
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-10 04:32:58

问题出在onSortEnd回调中:

代码语言:javascript
复制
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作为值,这显然不能在更新数组顺序时用作索引!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55081437

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档