- React 中的条件渲染和 js 中的一样,使用 js 运算符 if 或者条件运算符去创建元素来表现当前的状态,然后让 React 根据它们来更新 UI
function UserGreeting(props) {
return <h1>Welcome back!</h1>;
}
function GuestGreeting(props) {
return <h1>Please sign up.</h1>;
}
- 创建一个
Greeting
组件,它会根据用户是否登录来决定显示上面的哪一个组件
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}
ReactDOM.render(
<Greeting isLoggedIn={ false } />,
document.getElementById('root')
);
1. 元素变量
- 使用变量来储存元素,有条件地渲染组件,而其他的渲染部分并不会因此而改变
class LoginControl extends React.Component {
constructor(props) {
super(props);
this.handleLoginClick = this.handleLoginClick.bind(this);
this.handleLogoutClick = this.handleLogoutClick.bind(this);
this.state = { isLoggedIn: false };
}
handleLoginClick() {
this.setState({ isLoggedIn: true });
}
handleLogoutClick() {
this.setState({ isLoggedIn: false });
}
render() {
const isLoggedIn = this.state.isLoggedIn;
let button;
if (isLoggedIn) {
button = <LogoutButton onClick={ this.handleLogoutClick } />;
} else {
button = <LoginButton onClick={ this.handleLoginClick } />;
}
return (
<div>
<Greeting isLoggedIn={ isLoggedIn } />
{ button }
</div>
);
}
}
ReactDOM.render(
<LoginControl />,
document.getElementById('root')
)
2. 与运算符 &&
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. 阻止组件渲染
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')
)
-
<WarningBanner />
会根据prop
中warn
的值来进行条件渲染。如果warn
的值是false
,那么组件则不会渲染 -
在组件的
render
方法中返回null
并不会影响组件的生命周期