top
Loading...
React 條件渲染

React 條件渲染

在 React 中,你可以創建不同的組件來封裝各種你需要的行為。然後還可以根據應用的狀態變化只渲染其中的一部分。

React 中的條件渲染和 JavaScript 中的一致,使用 JavaScript 操作符 if 或條件運算符來創建表示當前狀態的元素,然後讓 React 根據它們來更新 UI。

先來看兩個組件:

function UserGreeting(props) {
  return <h1>歡迎回來!</h1>;
}
function GuestGreeting(props) {
  return <h1>請先注冊。</h1>;
}

我們將創建一個 Greeting 組件,它會根據用戶是否登錄來顯示其中之一:

React 實例

function Greeting(props) { const isLoggedIn = props.isLoggedIn; if (isLoggedIn) { return <UserGreeting />; } return <GuestGreeting />; } ReactDOM.render( // 嘗試修改 isLoggedIn={true}: <Greeting isLoggedIn={false} />, document.getElementById('example') );

嘗試一下 »

元素變量

你可以使用變量來儲存元素。它可以幫助你有條件的渲染組件的一部分,而輸出的其他部分不會更改。

在下面的例子中,我們將要創建一個名為 LoginControl 的有狀態的組件。

它會根據當前的狀態來渲染 <LoginButton /><LogoutButton />,它也將渲染前面例子中的 <Greeting />

React 實例

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 = null; 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('example') );

嘗試一下 »

與運算符 &&

你可以通過用花括號包裹代碼在 JSX 中嵌入任何表達式 ,也包括 JavaScript 的邏輯與 &&,它可以方便地條件渲染一個元素。

React 實例

function Mailbox(props) { const unreadMessages = props.unreadMessages; return ( <div> <h1>Hello!</h1> {unreadMessages.length > 0 && <h2> 您有 {unreadMessages.length} 條未讀信息。 </h2> } </div> ); } const messages = ['React', 'Re: React', 'Re:Re: React']; ReactDOM.render( <Mailbox unreadMessages={messages} />, document.getElementById('example') );

嘗試一下 »

在 JavaScript 中,true && expression 總是返回 expression,而 false && expression 總是返回 false

因此,如果條件是 true&& 右側的元素就會被渲染,如果是 false,React 會忽略併跳過它。


三目運算符

條件渲染的另一種方法是使用 JavaScript 的條件運算符:

condition ? true : false。

在下面的例子中,我們用它來有條件的渲染一小段文本。

render() { const isLoggedIn = this.state.isLoggedIn; return (
The user is {isLoggedIn ? 'currently' : 'not'} logged in.
); } 同樣它也可以用在較大的表達式中,雖然不太直觀:
render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      {isLoggedIn ? (
        <LogoutButton onClick={this.handleLogoutClick} />
      ) : (
        <LoginButton onClick={this.handleLoginClick} />
      )}
    </div>
  );
}

阻止組件渲染

在極少數情況下,你可能希望隱藏組件,即使它被其他組件渲染。讓 render 方法返回 null 而不是它的渲染結果即可實現。

在下面的例子中,<WarningBanner /> 根據屬性 warn 的值條件渲染。如果 warn 的值是 false,則組件不會渲染:

React 實例

function WarningBanner(props) { if (!props.warn) { return null; } return ( <div className="warning"> 警告! </div> ); } class Page extends React.Component { constructor(props) { super(props); this.state = {showWarning: true} this.handleToggleClick = this.handleToggleClick.bind(this); } handleToggleClick() { this.setState(prevState => ({ showWarning: !prevState.showWarning })); } render() { return ( <div> <WarningBanner warn={this.state.showWarning} /> <button onClick={this.handleToggleClick}> {this.state.showWarning ? '隱藏' : '顯示'} </button> </div> ); } } ReactDOM.render( <Page />, document.getElementById('example') );

嘗試一下 »

組件的 render 方法返回 null 併不會影響該組件生命周期方法的回調。例如,componentWillUpdate 和 componentDidUpdate 依然可以被調用。

北斗有巢氏 有巢氏北斗