gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:45:55 25 4
gpt4 key购买 nike

我正在尝试使用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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com