【发布时间】:2015-07-14 01:59:19
【问题描述】:
父组件(在我的示例中为MyList)组件通过子组件(MyComponent)呈现一个数组。 Parent决定更改数组中的属性,React触发child重新渲染的方式是什么?
在调整数据后,我想出的只是父级中的this.setState({});。这是 hack 还是触发更新的 React 方式?
JS 小提琴: https://jsfiddle.net/69z2wepo/7601/
var items = [
{id: 1, highlighted: false, text: "item1"},
{id: 2, highlighted: true, text: "item2"},
{id: 3, highlighted: false, text: "item3"},
];
var MyComponent = React.createClass({
render: function() {
return <div className={this.props.highlighted ? 'light-it-up' : ''}>{this.props.text}</div>;
}
});
var MyList = React.createClass({
toggleHighlight: function() {
this.props.items.forEach(function(v){
v.highlighted = !v.highlighted;
});
// Children must re-render
// IS THIS CORRECT?
this.setState({});
},
render: function() {
return <div>
<button onClick={this.toggleHighlight}>Toggle highlight</button>
{this.props.items.map(function(item) {
return <MyComponent key={item.id} text={item.text} highlighted={item.highlighted}/>;
})}
</div>;
}
});
React.render(<MyList items={items}/>, document.getElementById('container'));
【问题讨论】:
标签: javascript reactjs