MyComponent 的 state 中包含一个布尔值,用于跟踪是否要在 UI 中显示某个元素。按钮切换此值的状态。目前,它每次都呈现相同的 UI。用if/else语句重写render()方法,如果display为true则返回当前标记。否则,返回不带h1元素的标记。
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
display: true
}
this.toggleDisplay = this.toggleDisplay.bind(this);
}
toggleDisplay() {
this.setState({
display: !this.state.display
});
}
render() {
// change code below this line
if(this.state.display){
return (
<div>
<button onClick={this.toggleDisplay}>Toggle Display</button>
<h1>Displayed!</h1>
</div>
);
}else{
return (
<div>
<button onClick={this.toggleDisplay}>Toggle Display</button>
</div>
);
}
}
};
方式二,使用 && 获得更简洁的条件
如果condition为 true,则返回标记。如果 condition 为 false,操作将在判断condition后立即返回false,并且不返回任何内容。你可以将这些语句直接包含在 JSX 中,并通过在每个条件后面写&&来将多个条件串在一起。这允许你在render()方法中处理更复杂的条件逻辑,而无需重复大量代码。
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
display: true
}
this.toggleDisplay = this.toggleDisplay.bind(this);
}
toggleDisplay() {
this.setState({
display: !this.state.display
});
}
render() {
// change code below this line
return (
<div>
<button onClick={this.toggleDisplay}>Toggle Display</button>
{this.state.display && <h1>Displayed!</h1>}
</div>
);
}
};