Files
2018-10-16 21:32:40 +05:30

37 lines
900 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: Render with an If/Else Condition
localeTitle: 使用If / Else条件渲染
---
## 使用If / Else条件渲染
### 方法
在组件的render方法内部编写if / else语句每个语句都有自己的返回方法该方法具有不同的JSX。这使程序员能够根据各种条件呈现不同的UI。
首先将当前返回方法包装在if语句中并设置条件以检查变量'display'是否为true。请记住您使用`this.state`访问状态。
### 解
```react.js
if (this.state.display === true) {
return (
<div>
<button onClick={this.toggleDisplay}>Toggle Display</button>
<h1>Displayed!</h1>
</div>
);
}
```
接下来创建一个else语句返回**不带** `h1`元素的相同JSX。
```react.js
else {
return (
<div>
<button onClick={this.toggleDisplay}>Toggle Display</button>
</div>
)
}
```