Javascript 如何在reactjs中使用条件语句呈现组件?
这是我的示例代码Javascript 如何在reactjs中使用条件语句呈现组件?,javascript,node.js,reactjs,if-statement,jsx,Javascript,Node.js,Reactjs,If Statement,Jsx,这是我的示例代码 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 PortfolioContaine
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;
import React,{Component}来自“React”;
从“/Navpills”导入Navpills;
从“/pages/Home”导入主页;
从“/pages/About”导入关于;
从“/pages/Blog”导入博客;
从“/pages/Contact”导入联系人;
类PortfolioContainer扩展组件{
状态={
当前页面:“主页”
};
handlePageChange=页面=>{
this.setState({currentPage:page});
};
render(){
返回(
基于“this.state.currentPage”,呈现适当的组件
在这里
);
}
}
导出默认PortfolioContainer;
说明如下:
现在将代码添加到PortfolioContainer
,以便根据当前选择的页面,在Navpills
组件下面呈现不同的组件。例如:
- 当
this.state.currentPage==“About”
- 当
this.state.currentPage==“Blog”
- 当
this.state.currentPage==“Contact”
- 当
this.state.currentPage==“Home”
render() {
return (
<div>
<Navpills
currentPage={this.state.currentPage}
handlePageChange={this.handlePageChange}
/>
{this.state.currentPage === "About" && <About />}
here.
</div>
);
}
render(){
返回(
{this.state.currentPage===“About”&.有几种方法可以做到这一点,这里有一个例子:
此外,还有以下软件包:
或者,您可以通过以下简洁的方式:
{this.state.currentPage==“About”&&& 文档中也有一个页面,欢迎使用stackoverflow。您并没有真正提出问题,而是粘贴了一些类似家庭作业的内容?查看此页面,了解如何提出一个好问题。据我所知,问题中的代码仅用于学习目的。如果这是一个实际应用程序,您肯定应该使用反应路由器。