首頁  >  文章  >  web前端  >  react渲染方式的幾種是什麼

react渲染方式的幾種是什麼

青灯夜游
青灯夜游原創
2022-03-22 14:06:312917瀏覽

react渲染方式有:1、利用條件表達式渲染,適用於兩個元件二選一的渲染;2、利用「&&」操作符渲染,適用於一個元件有無的渲染;3 、利用變數輸出元件渲染;4、利用函數方法輸出元件或利用函數式元件進行渲染。

react渲染方式的幾種是什麼

本教學操作環境:Windows7系統、react17.0.1版、Dell G3電腦。

React 元件條件渲染的幾種方式

#一、條件表達式渲染(適用於兩個元件二選一的渲染)

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      {isLoggedIn ? (
        <LogoutButton onClick={this.handleLogoutClick} />
      ) : (
        <LoginButton onClick={this.handleLoginClick} />
      )}
    </div>
  );
}

二、&& 運算子渲染 (適用於一個元件有無的渲染)

function Mailbox(props) {
  const unreadMessages = props.unreadMessages;
  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 &&
        <h2>
          You have {unreadMessages.length} unread messages.
        </h2>
      }
    </div>
  );
}

#三、利用變數輸出元件渲染 (適用於有多個元件多種條件下的渲染)

render() {
    const isLoggedIn = this.state.isLoggedIn;
 
    const button = isLoggedIn ? (
      <LogoutButton onClick={this.handleLogoutClick} />
    ) : (
      <LoginButton onClick={this.handleLoginClick} />
    );
 
    return (
      <div>
        <Greeting isLoggedIn={isLoggedIn} />
        {button}
      </div>
    );
  }

四、利用函數方法輸出元件或利用函數式元件來渲染 (適用於多個子元件需要根據複雜的條件輸出的情況)

1.函數方式

renderButton(){
    const isLoggedIn = this.state.isLoggedIn;
    if(isLoggedIn)
    {
       return (<LogoutButton onClick={this.handleLogoutClick} />);
    }
    else
    {
      return (<LoginButton onClick={this.handleLoginClick} />);
    }
}
 
render() {
    return (
      <div>
        <Greeting />
        {this.renderButton()}
      </div>
    );
  }

2. 函數式元件

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
}
 
ReactDOM.render(
  // Try changing to isLoggedIn={true}:
  <Greeting isLoggedIn={false} />,
  document.getElementById(&#39;root&#39;)
);

【相關推薦: Redis影片教學

以上是react渲染方式的幾種是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn