Here's a simple React component that displays a list, when a list item gets clicked, the element adds a class name with a name selected.
var CX = React.addons.classSet;
var List = React.createClass({
getInitialState: function(){
return {
items: this.props.items
}
},
handleItemClick: function(item){
item.isSelected = true;
this.forceUpdate();
},
render: function(){
var self = this;
var items = this.state.items.map(function(item, index){
var className = CX({
'item': true,
'selected': item.isSelected
});
return (
<li key={index}
onClick={self.handleItemClick.bind(self, item)}
className={className}>
item.name
</li>
);
});
return (
<ul>
{items}
</ul>
);
}
});
var items = [{
name: 'Apple',
value: 1
}, {
name: 'Microsoft',
value: 2
}];
React.renderComponent(<List items={items} />, document.body);
Question: because it stateis a reference type that contains an array of an object, and in the event handler handleItemClickI get only the corresponding one item. I am currently mutating itemdirectly, then invoking this.forceUpdate(), the result will be as expected.
However, as the React documentation suggests, mutating statedirectly is bad behavior, and I come across another method that uses React.addons.updateto mutate a complex object, but I didn't get it working.
, - , ? !
React.addons.update