React 전체 선택 및 반전

3635 단어

CheckboxList.js

class CheckboxList extends React.Component{
  constructor(props){
    super(props)
    this.state = {
      data: [
        { 'name':'red', 'checked': true },
        { 'name':'green', 'checked': false },
        { 'name':'blue', 'checked': false }
      ],
      checkedAll: false, // 
      checkedInvert: false // 
    }
    this.handleAllChange = this.handleAllChange.bind(this);
    this.handleInvertChange = this.handleInvertChange.bind(this);
    this.handleItemChange = this.handleItemChange.bind(this);
  }

  //  
  handleAllChange(){
    const { checkedAll,data } = this.state;

    data.map(function(item,index){
      return item.checked = !checkedAll;
    })

    this.setState({
      checkedAll: !checkedAll,
      checkedInvert: false,
      data: data
    });
  }

  //  
  handleInvertChange(){
    const { checkedInvert, data } = this.state;

    data.map(function(item,index){
      return item.checked = !item.checked;
    })

    const checkedAll = data.every(function(item,index){
      return item.checked;
    })

    this.setState({
      checkedAll: checkedAll,
      checkedInvert: !checkedInvert,
      data: data
    });
  }

  // CheckItem 
  handleItemChange(ckitem){
    const data = this.state.data;
    const checked = ckitem.checked;
    let checkedInvert = this.state.checkedInvert;

    data.map(function(item,index){
      if(item.name === ckitem.name){
        return item.checked = ckitem.checked
      }
    })

    const checkedAll = data.every(function(item,index){
      return item.checked;
    })

    checkedInvert = checkedAll ? false : checkedInvert;

    this.setState({
      data: data,
      checkedAll: checkedAll,
      checkedInvert: checkedInvert
    })
  }

  renderList(){
    var that = this;
    return this.state.data.map(function(item,index){
      return 
    })
  }

  render(){
    const {checkedAll,checkedInvert} = this.state
    return(
      
{this.renderList()}
) } }

CheckboxItem.js

class CheckboxItem extends React.Component{
  constructor(props){
    super(props)
    this.state = {
      checked: props.checked,
      name: props.name
    }
    this.handleChange = this.handleChange.bind(this);
  }

  componentWillReceiveProps(nextProps,prevProps){
    if(nextProps.checked != prevProps.checked){
      this.setState({
        checked: nextProps.checked
      })
    }
  }

  handleChange(){
    const { checked,name } = this.state
    this.setState({
      checked: !checked
    },function(){
      this.props.handleItemChange({ name: name, checked: !checked });
    })
  }

  render(){
    const {checked,name} = this.state
    return(
      
) } }

App.js

ReactDOM.render(
  ,
  document.getElementById('root')
);

효과 미리 보기http://m.pengjielee.cn/htmls/checkall.html

좋은 웹페이지 즐겨찾기