react多選框

react多選框數組裏,須要定義checked屬性。react

import React, { Component } from 'react' class App extends Component { constructor(props) { super(props); this.state = { checkboxItems:[ {content:"吃",checked:false}, {content:"喝",checked:false}, {content:"玩",checked:false}, {content:"樂",checked:false}, ] } } render() { return ( <div> { this.state.checkboxItems.map((ele,index)=>{ return ( <span key={index}>
               <input type="checkbox" name="" value={index} checked={ele.checked} onChange={()=>this.getVal(index)}/><span>{ele.content}</span>
            </span>
 ) }) } </div>
 ); } getVal = (index)=>{ //複製原來的數組
    var items = [...this.state.checkboxItems] //checked取反
    items[index].checked =!items[index].checked this.setState({ //更新checkboxItems所有選項
 checkboxItems:items }) } } export default App;
相關文章
相關標籤/搜索