2017-07-07 540 views
1

我正在尝试使用react-sortable-hoc的示例。可排序无法保持排序状态。看看GIF。react-sortable-hoc reactJS库排序问题

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; 

不知道为什么,这个库是不是保持状态?

感谢

回答

0

在你SortableList,你设置基于当前索引,这是做正常的事情的关键,但它似乎是什么原因造成的问题。使关键字匹配值,而它似乎按预期工作。

我猜想关键需要与底层组件一起移动。

const SortableList = SortableContainer(({ items }) => { 
    return (
    <div> 
     {items.map((value, index) => (
     <SortableItem key={`item-${value}`} index={index} value={value} /> 
    ))} 
    </div> 
); 
}); 
+0

感谢它的工作!我遗漏了SortableItem中的键 – HarshMakadia