【问题标题】:How to render a component using a conditional statement in reactjs? [duplicate]如何在 reactjs 中使用条件语句渲染组件? [复制]
【发布时间】:2018-06-18 20:44:14
【问题描述】:

这是我的示例代码。

import React, { Component } from "react";
import Navpills from "./Navpills";
import Home from "./pages/Home";
import About from "./pages/About";
import Blog from "./pages/Blog";
import Contact from "./pages/Contact";

class PortfolioContainer extends Component {
  state = {
    currentPage: "Home"
  };

  handlePageChange = page => {
    this.setState({ currentPage: page });
  };

  render() {
    return (
      <div>
        <Navpills
          currentPage={this.state.currentPage}
          handlePageChange={this.handlePageChange}
        />
        Based on `this.state.currentPage`, render the appropriate component
        here.
      </div>
    );
  }
}

export default PortfolioContainer;

说明如下:

现在将代码添加到PortfolioContainer,以便根据当前选择的页面,在Navpills 组件下方呈现不同的组件。示例:

  • this.state.currentPage === "About"时渲染About组件

  • this.state.currentPage === "Blog"时渲染Blog组件

  • this.state.currentPage === "Contact"时渲染Contact组件

  • this.state.currentPage === "Home"时渲染Home组件

【问题讨论】:

标签: javascript node.js reactjs if-statement jsx


【解决方案1】:

您可以使用以下语法有条件地渲染组件:

render() {
    return (
      <div>
        <Navpills
          currentPage={this.state.currentPage}
          handlePageChange={this.handlePageChange}
        />
        {this.state.currentPage === "About" && <About />}
        here.
      </div>
    );
  }

但在您的情况下,使用react-router 可能会更好。

【讨论】:

  • 据我了解,问题中的代码仅用于学习目的。如果是实际应用,一定要使用 react-router。
【解决方案2】:

有几种方法可以做到这一点 React 文档在这里有一个示例:https://reactjs.org/docs/conditional-rendering.html

还有这个包:https://www.npmjs.com/package/react-render-if

或者你可以做这种简洁的方式: {this.state.currentPage === "关于" && }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 2020-06-13
    • 2020-09-04
    • 2019-04-25
    • 2016-10-21
    相关资源
    最近更新 更多