簡體   English   中英

你如何在 React 中使用子組件實現“全部檢查”?

[英]How do you implement “check all” in React with child components?

我在這里找到了幾個問題來回答這個問題,

但它們不允許我渲染帶有復選框的組件。

我想要的是這樣的

render: function () {
    var rows = [<ChildElement key={1} />, <ChildElement key={2} />];
    return (
    <ParentElement>{rows}</ParentElement>
    );
}

我的 ChildElements 每個都有自己的復選框,只要在 ParentElement 上選中或取消選中全局復選框,就可以將其設置為checked=truechecked=false

有什么建議? 干杯

我整理了一個要點供您嘗試,但基本思想是維護父項中復選框的狀態,並在子項中進行回調以傳遞其更改的狀態。

http://jsfiddle.net/69z2wepo/4785/

var Row = React.createClass({
  getInitialState: function() {
    return {
      checked: false
    };
  },
  checkIt: function() {
    this.props.callback(this.props.index, !this.props.checked);
    return;
  },
  render: function() {
    return (
      <tr>
        <td><input type="checkbox" checked={this.props.checked} onChange={this.checkIt} /></td>
        <td>{this.props.obj.foo}</td>
      </tr>
    );
  }
});

var Table = React.createClass({
  getInitialState: function() {
    var rowState =[];
    for(var i = 0; i < this.props.rows.length; i++) {
      rowState[i] = false;
    }
    return {
      checkAll: false,
      rowState:rowState
    };
  },
  checkRow: function (id,value) {
    this.state.rowState[id] = value;
    if (this.state.checkAll) {
      this.state.checkAll = !this.state.checkAll;
    }
    this.setState({
      rowState: this.state.rowState,
      checkAll: this.state.checkAll
    });
  },
  checkAll: function () {
    var rowState =[];
    var checkState = !this.state.checkAll;
    for(var i = 0; i < this.state.rowState.length; i++) {
      rowState[i] = checkState;
    }

    this.state.checkAll = checkState;

    this.setState({
      rowState: rowState,
      checkAll: this.state.checkAll
    });
  },
  render: function() {
    var self = this;

    var rows = _.map(this.props.rows, function( row,index) {
      return (<Row obj={row} index={index} key={row.id} checked={self.state.rowState[index]} callback={self.checkRow} />);
    });
    return (
      <div className="table-holder container">
      <input type="checkbox" checked={this.state.checkAll} onChange={this.checkAll} />
      <table className="table">{rows}</table>
      </div>
    );
  }
});

var rows = [
  {
    'id' : 1,
    'foo': 'bar'
  },
  {
    'id' : 2,
    'foo': 'baarrrr'
  },
  {
    'id' : 3,
    'foo': 'baz'
  }
];

React.render(<Table rows={rows}/>, document.getElementById('container'));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM