2017-06-01 44 views
0

我有2个对象数组,一个是预加载列表,一个是选定的项目。我的问题是无法在复选框上选中所选项目。map 2使用findIndex对象的数组es6

https://jsfiddle.net/8usvfzv9

class HelloWidget extends React.Component { 
    constructor(props) { 
     super(props); 
     this.list = [{ 
     "id": "exhibitions", 
     "name": "Exhibitions" 
     }, { 
     "id": "festivals_n_concerts", 
     "name": "Festivals & Concerts" 
     }, { 
     "id": "grand_opening", 
     "name": "Grand Opening" 
     }, { 
     "id": "meeting", 
     "name": "Meeting" 
     }, { 
     "id": "party", 
     "name": "Party" 
     }, { 
     "id": "product_launches", 
     "name": "Product Luanches" 
     }, { 
     "id": "roadshows", 
     "name": "Roadshows" 
     }, { 
     "id": "sporting_events", 
     "name": "Sporting Events" 
     }, { 
     "id": "trade_show", 
     "name": "Trade Show" 
     }] 

     this.selectedList = [{ 
     "id": "grand_opening", 
     "name": "Grand Opening", 
     "space_event_id": "grand_opening" 
     }, { 
     "id": "trade_show", 
     "name": "Trade Show", 
     "space_event_id": "trade_show" 
     }] 
    } 

    render() { 
     return (<div> 
     {this.list.map(obj => <div><br /><input 
     key={obj.name} 
     checked={this.selectedList.findIndex(o => o.id === obj.id)} 
     type="checkbox" >{obj.name}</input></div>)} 
     </div> 
     ) 
     } 
} 

我觉得这条线是错误的

checked={this.selectedList.findIndex(o => o.id === obj.id)}

底座上的输出结果。任何线索如何使用findIndex?

回答

0

为选中道具只适用于布尔和findIndex回报号码,就可以如下修改:

checked={this.selectedList.findIndex(o => o.id === obj.id) !== -1} 
+0

尽管此代码可以回答这个问题,提供了关于如何和/或为什么它解决了额外的上下文问题会提高答案的长期价值。 – Badacadabra

+0

@Badacadabra。接受〜 – Jin