react多选框

Posted on 2019-07-16 14:55  猫头唔食鱼  阅读(2511)  评论(0编辑  收藏  举报

react多选框数组里,需要定义checked属性。

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;