在以下示例中,Item 2
单击 时Second 1
会显示 而不是Second 2
。为什么?你会如何解决这个问题?
var guid = 0;
class Content extends React.Component {
constructor() {
guid += 1;
this.id = guid;
console.log('ctor', this.id); // called only once with 1
}
render() {
return (
<div className="content">
{this.props.title} - {this.id}
</div>
);
}
}
class MyApp extends React.Component {
constructor() {
this.items = ['Item 1', 'Item 2'];
this.state = {
activeItem: this.items[0]
};
}
onItemClick(item) {
this.setState({
activeItem: item
});
}
renderMenu() {
return (
<div className="menu">
<div onClick={this.onItemClick.bind(this, 'Item 1')}>Item 1</div>
<div onClick={this.onItemClick.bind(this, 'Item 2')}>Item 2</div>
</div>
);
}
renderContent() {
if (this.state.activeItem === 'Item 1') {
return (
<Content title="First" />
);
} else {
return (
<Content title="Second" />
);
}
}
render() {
return (
<div>
{this.renderMenu()}
{this.renderContent()}
</div>
);
}
}