條件渲染
1:render函數(shù)里寫判斷
render() {
if(){
}
}
2:與運算符 &&
之所以能這樣做,是因為在 JavaScript 中,`true && expression` 總是會返回 `expression`, 而 `false && expression` 總是會返回 `false`。
因此,如果條件是 `true`,`&&` 右側(cè)的元素就會被渲染,如果是 `false`,React 會忽略并跳過它。
### [](https://react.docschina.org/docs/conditional-rendering.html#inline-if-else-with-conditional-operator)
function Mailbox(props) {
const unreadMessages = props.unreadMessages;
return (
<div>
<h1>Hello!</h1>
{unreadMessages.length > 0 &&
<h2>
You have {unreadMessages.length} unread messages.
</h2>
}
</div>
);
}
const messages = ['React', 'Re: React', 'Re:Re: React'];
ReactDOM.render(
<Mailbox unreadMessages={messages} />,
document.getElementById('root')
);
3:三目運算符
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
</div>
);
}
和
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
{isLoggedIn
? <LogoutButton onClick={this.handleLogoutClick} />
: <LoginButton onClick={this.handleLoginClick} />
}
</div>
);
}
4:阻止組件渲染
在極少數(shù)情況下,你可能希望能隱藏組件,即使它已經(jīng)被其他組件渲染。若要完成此操作,你可以讓 render 方法直接返回 null,而不進行任何渲染。
下面的示例中,<WarningBanner /> 會根據(jù) prop 中 warn 的值來進行條件渲染。如果 warn 的值是 false,那么組件則不會渲染:
function WarningBanner(props) {
if (!props.warn) {
return null;
}
return (
<div className="warning">
Warning!
</div>
);
}
class Page extends React.Component {
constructor(props) {
super(props);
this.state = {showWarning: true};
this.handleToggleClick = this.handleToggleClick.bind(this);
}
handleToggleClick() {
this.setState(state => ({
showWarning: !state.showWarning
}));
}
render() {
return (
<div>
<WarningBanner warn={this.state.showWarning} />
<button onClick={this.handleToggleClick}>
{this.state.showWarning ? 'Hide' : 'Show'}
</button>
</div>
);
}
}
ReactDOM.render(
<Page />,
document.getElementById('root')
);
在組件的 render 方法中返回 null 并不會影響組件的生命周期。例如,上面這個示例中,componentDidUpdate 依然會被調(diào)用。