React的几种条件渲染

3,259 阅读2分钟

      对于一个展示页面来讲,有好几种展示状态,在React中,可以根据不同的状态,渲染组件。也就是条件渲染。不同于Vue的v-if,v-show等框架提供的api,React中的条件渲染的工作方式与JavaScript中条件工作的方式相同。

以下就是条件渲染的几种方法:

方法一:

创建两个组件,根据条件显示两个组件之一(if-else)

举例:

 function OneRender(props) {
  return <h1>Welcome one</h1>;
 }

function TwoRender(props) {
  return <h1>Welcome two.</h1>;
}

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <OneRender />;
  }
  return <TwoRender />;
}

ReactDOM.render(
  // Try changing to isLoggedIn={true}:
  <Greeting isLoggedIn={false} />,
  document.getElementById('root')
);

方法二:

使用变量来存储元素,这样可以有条件地渲染组件的部分,剩余部分保持不变。

举例:

function LoginButton(props) {
  return (
    <button onClick={props.onClick}>
      Login
    </button>
  );
}

function LogoutButton(props) {
  return (
    <button onClick={props.onClick}>
      Logout
    </button>
  );
}

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('root')
);

方法三:

行内判断是否渲染,将所有表达式括在花括号中,从而将其嵌入JSX中。

举例:

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')
);

方法四:

内联条件渲染元素使用JavaScript的三元表达式。

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
    </div>
  );
}

方法五:

阻止组件渲染,在有些情况下,希望某个组件隐藏自身,即使该组件是由另一个组件渲染也是如此。可以返回null而不是其渲染输出。null从组件的render方法返回不会影响组件生命周期方法的触发。

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(prevState => ({
      showWarning: !prevState.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')
);

以上就是React的几种条件渲染的方法,在实际做项目当中,选哪一种条件渲染可以根据自己的需求来进行选择。(ps:根据react官网翻译来,做个总结,加深自己对条件渲染的理解)。一起加油吧!