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

謝謝,它的工作原理。 –

相關問題