React.js修改父按钮的状态

时间:2015-04-15 04:10:33

标签: javascript reactjs

我正在深入研究Reactjs。在我粗略的例子中,我希望删除按钮从items数组中删除一个项目。我如何通过在Btn组件中的handleClick来做到这一点?或者处理这个问题的最佳方法是什么?

var data= {
"items": [
    {
        "title": "item1"
    },
    {
        "title": "item2"
    },
    {
        "title": "item3"
    }
]
};



var Btn = React.createClass({

handleClick: function(e) {
console.log('clicked delete'+ this.props.id);
  //how does delete button modify this.state.items in TodoApp?

},
render: function() {
return <button onClick={this.handleClick}>Delete</button>;
}
});

var TodoList = React.createClass({

render: function() {
var createItem = function(itemText, index) {
  return <li key={index + itemText}>{itemText} &nbsp;<Btn id={index} /></li>;
};
return <div><ul>{this.props.items.map(createItem)}</ul></div>;
}
});



var TodoApp = React.createClass({

getInitialState: function() {
  console.log("getInitialState");

return data;
  },



  onChange: function(e) {
    this.setState({text: e.target.value});
  },
  handleSubmit: function(e) {
    e.preventDefault();
    var nextItems = this.state.items.concat([this.state.text]);
    var nextText = '';
    this.setState({items: nextItems, text: nextText});
  },
  render: function() {
    return (
      <div>
        <h3>TODO</h3>
        <TodoList items={this.state.items} />
        <form onSubmit={this.handleSubmit}>
          <input onChange={this.onChange} value={this.state.text} />
          <button>{'Add #' + (this.state.items.length + 1)}</button>
        </form>
      </div>
    );
  }
});



React.render(<TodoApp />, document.getElementById('container'));

JSFiddle example

2 个答案:

答案 0 :(得分:0)

向您的Btn组件发送回调。在this answer中进一步解释。

答案 1 :(得分:0)

Flux的方式是更新您的数据存储并触发您的应用渲染,f.ex:

var deleter = function(id) {
  data.items.splice(id,1)
  React.render(<TodoApp />,
    document.getElementById('container'));
}

[...]

handleClick: function(e) {
    deleter(this.props.id)
}

演示:http://jsfiddle.net/s01f1a4a/