reactjs - 是否可以在 React 渲染函数中使用 if...else... 语句?

标签 reactjs

基本上,我有一个react组件,它的render()函数体如下:(这是我理想的一个,这意味着它目前不起作用)

render(){
    return (
        <div>
            <Element1/>
            <Element2/>

            // note: logic only, code does not work here
            if (this.props.hasImage) <ElementWithImage/>
            else <ElementWithoutImage/>

        </div>
    )
}

最佳答案

不完全一样,但有解决方法。 React's docs中有一个部分关于条件渲染,你应该看看。以下是使用内联 if-else 可以执行的操作的示例。

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

您还可以在渲染函数内处理它,但在返回 jsx 之前。

if (isLoggedIn) {
  button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
  button = <LoginButton onClick={this.handleLoginClick} />;
}

return (
  <div>
    <Greeting isLoggedIn={isLoggedIn} />
    {button}
  </div>
);

还值得一提的是 ZekeDroid 在评论中提出的内容。如果您只是检查条件并且不想呈现不符合条件的特定代码段,则可以使用 && 运算符

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

关于reactjs - 是否可以在 React 渲染函数中使用 if...else... 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40477245/

相关文章:

jquery - <svg> 掩码在用于在 react.js 中显示 svg <image> 时不起作用

javascript - 找不到模块 'react/jsx-runtime' 的声明文件

css - 在微调器/加载器运行时禁用背景

reactjs - react native 和 typescript 多内联样式

javascript - React 中的深度比较对象属性未按预期工作

javascript - kendoui 网格和 react : selectable row allows to select one row in each page

reactjs - import 'useAuthenticator' from aws-amplify 在 Jest 测试时输出 "TypeError: window.URL.createObjectURL is not a function"

reactjs - React 函数式/无状态纯组件

android - 为什么 React Native Picker 在我的 Android 模拟器中无法工作?

javascript - Laravel 5.5 使用来自 Controller 的数据在 Blade View 中呈现 React 组件