我正在做我的第一个反应项目。我是JS,HTML,CSS甚至Web应用程序编程的新手。
我想做的是在单击按钮时显示一些信息。
我有主要的默认组件 App.js
。看起来像这样:
import React, { Component } from "react";
import Navbar from "./Components/Navbar";
import "./Styles/App.css";
import ProjectsList from "./Components/Projects/ProjectsList";
import axios from "axios";
class App extends Component {
state = {
projects: [], //i get it from api on Didmount();
showProjects: true //hardcoded var to shows projects list
};
componentDidMount() {
//i get projects here from axios and my api, it works ok!
}
render() {
return (
<div>
<Navbar />
{this.state.showProjects && (
<ProjectsList projects={this.state.projects} />
)}
</div>
);
}
}
export default App;
如您所见,我可以通过硬编码的ProjectLists
布尔值来操纵showprojects
的可见性。可以。如果为false则不可见,为true则很简单。
如何将showProjects
变量传输到我的Navbar.js
组件并通过单击导航栏项来触发它?
我的 Navbar.js
:
import React, { Component } from "react";
import { Navbar } from "react-bootstrap";
class NavBar extends Component {
render() {
return (
<Navbar inverse collapseOnSelect>
<Navbar.Collapse>
<Navbar.Form>
<Navbar.Brand> Projects </Navbar.Brand> //button click here, how to?
</Navbar.Form>
</Navbar.Collapse>
</Navbar>
);
}
}
export default NavBar;
视图如下:
我希望可以选择在导航栏中单击Projects
,然后将我的ShowProjects
设置为true,并且可以看到项目。该怎么做?
感谢您的任何建议!
编辑:
如果有帮助,请使用我的 ProjectsList.js
组件:
import React, { Component } from "react";
import Project from "./Project";
import { ListGroup } from "react-bootstrap";
class ProjectsList extends Component {
render() {
return (
<ListGroup>
{this.props.projects.map(project => {
return <Project project={project} key={project.id} />;
})}
</ListGroup>
);
}
}
export default ProjectsList;
答案 0 :(得分:2)
首先在父组件中创建状态更改函数:
toggleShowProjects = () => {
this.setState(prevState => ({
showProjects: !prevState.showProjects
}))
}
将函数传递给Navbar组件:
import React, { Component } from "react";
import Navbar from "./Components/Navbar";
import "./Styles/App.css";
import ProjectsList from "./Components/Projects/ProjectsList";
import axios from "axios";
class App extends Component {
state = {
projects: [], //i get it from api on Didmount();
showProjects: true //hardcoded var to shows projects list
};
componentDidMount() {
//i get projects here from axios and my api, it works ok!
}
toggleShowProjects = () => {
this.setState(prevState => ({
showProjects: !prevState.showProjects
}))
}
render() {
return (
<div>
<Navbar
toggleProjects={this.toggleShowProjects} />
{this.state.showProjects && (
<ProjectsList
projects={this.state.projects} />
)}
</div>
);
}
}
export default App;