Reactjs onClick:如何设置列表中单击按钮的状态

时间:2016-09-23 14:25:21

标签: javascript reactjs babeljs

我有一个按钮列表,我试图弄清楚如何获得所选择的每个按钮的state(所以在任何时候我都知道哪个按钮有/已被点击):

// this.state.selectedTransport:
{ car: true,  train: false, plane: true } or
{ car: false, train: false, plane: true } or
{ car: true,  train: true,  plane: true } etc

请在此处查看代码: http://jsbin.com/gizamovaco/1/edit?html,js,console,output

2 个答案:

答案 0 :(得分:2)

主要思想是在父组件中使用handleClick函数,然后在子组件中调用它来更新父级的状态,然后将其作为道具传递给不同的子级。我遵循了您现有的结构,结果如下:JSbin

答案 1 :(得分:0)

这样的事情会起作用:

//Child
var SingleButton = React.createClass({
  render: function() {
    let { selectedTransport, type, text, handleClick } = this.props;
    let selected = selectedTransport[type];
    var style = selected ? { "backgroundColor":"yellow" } : {
      "backgroundColor":""
    };
    return (
      <button style={style} onClick={handleClick} name={type}> 
        {text}
      </button>
    )
  }
});

//Parent
var Categories = React.createClass({
  getInitialState: function() {
    return { 
      selectedTransport: {
        car: false,
        train: false,
        plane: false
      }
    }
  },
  handleClick: function(event) {
    console.log('CLICK');
    let { selectedTransport } = this.state;
    selectedTransport[event.target.name] = true;
    this.setState({ selectedTransport });
    console.log('TRANSPORT', this.state.selectedTransport);
  },

  render: function() {
    console.log('RENDERING', this.state);
    var transportType = ['car', 'train', 'plane'];
    return (
      <div>
        {transportType.map((type, idx) => (
          <SingleButton 
            {...this.state}
            text={type} 
            handleClick={this.handleClick} 
            key={idx} 
            type={type} 
          />
        ))
      </div>
    );
  }
});


ReactDOM.render(<Categories />, document.getElementById('app'));