gpt4 book ai didi

javascript - 如何在reactjs中使用条件语句渲染组件?

转载 作者:行者123 更新时间:2023-12-03 02:44:08 25 4
gpt4 key购买 nike

这是我的示例代码。

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下方。成分。示例:

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

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

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

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

最佳答案

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

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

但就您而言,最好使用 react-router .

关于javascript - 如何在reactjs中使用条件语句渲染组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48174558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com