0

我正在尝试使用react.js库“react-sortable-hoc”(https://github.com/clauderic/react-sortable-hoc)创建一个可排序列表。将参数传递给使用ES6的React组件

在“SortableList”我映射阵列中的每个元件,其(应)创建一个“SortableElement”与参数索引上的功能。这就是“SortableElement”的定义是:https://github.com/clauderic/react-sortable-hoc/blob/master/src/SortableElement/index.js

SortableItem = SortableElement(({value,key}) => 
    <Row> 
     <this.DragHandle/> 
     <ControlLabel>Question</ControlLabel> 
     <FormControl 
     componentClass="textarea" 
     placeholder="Enter question" 
     onChange={()=> { 
      console.log(key);  //why undefined?? 
      console.log(value); 
     } 
     } 
     /> 
    </Row>); 

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

不幸的是,关键指数总是不确定的,我只是不明白为什么。如果您对完整代码感兴趣,请访问https://github.com/rcffc/react-dnd-test/blob/master/src/SortableComponent.js

任何帮助表示赞赏。

回答

1

如果您查看react-sortable-hoc的来源,您会发现在渲染中传递道具时,index被忽略。另外,key不会通过道具。如果您在SortableItem中更改解构日志道具,您会看到一个仅包含值('问题1','问题2'等)的对象。如果您需要访问索引或密钥,请将它们作为不同的道具传递。

例如

SortableItem = SortableElement(({value,yourIndex}) => 
    <Row> 
     <this.DragHandle/> 
     <ControlLabel>Question</ControlLabel> 
     <FormControl 
     componentClass="textarea" 
     placeholder="Enter question" 
     onChange={()=> { 
      console.log(yourIndex); 
      console.log(value); 
     } 
     } 
     /> 
    </Row> 
); 

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

对,我需要访问SortableElement中的键。说“把它们作为不同的道具”是什么意思? –

+0

注意我在示例中传递的'yourIndex' prop。将其重命名为适当的。 – Lee

+0

谢谢,它的工作原理。 –

相关问题