作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我的示例代码。
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/
我是一名优秀的程序员,十分优秀!