react中的條件渲染

條件渲染
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)用。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容