我正在尝试根据我点击的导航栏文本呈现不同的组件。渲染组件将替换当前组件。我有 5 个要使用的 onclick 元素,并按需呈现 5 个不同的组件。请帮忙!!
import Sidenav from "./components/ButtonAppBar";
import AboutTab from "./components/About";
import QuoteTab from "./components/Quote";
import ProductTab from "./components/Quote";
import CalendarTab from "./components/Quote";
import ContactTab from "./components/Quote";
import "./App.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
component: "About"
};
}
var component = this.state.component;
switch(component) {
case "Contact":
return <ContactTab />;
break;
case "Quote":
return <QuoteTab />;
break;
default:
return <AboutTab />;
}
render() {
return (
<div>
<Sidenav>
<h1 className="navlink" onClick={this.getComponent}>
About
</h1>
<h1 className="navlink" onClick={this.getComponent}>
Quote
</h1>
<h1 className="navlink" onClick={this.getComponent}>
Schedule
</h1>
<h1 className="navlink" onClick={this.getComponent}>
Products
</h1>
</Sidenav>
<AboutTab />
<QuoteTab />
</div>
);
}
}
export default App;
到目前为止,我卡住了,什么都做不了。
最佳答案
考虑到您正在使用元素内容字符串,您可以像这样重构您的 View :
import Sidenav from "./components/ButtonAppBar";
import AboutTab from "./components/About";
import QuoteTab from "./components/Quote";
import ProductTab from "./components/Quote";
import CalendarTab from "./components/Quote";
import ContactTab from "./components/Quote";
import "./App.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
component: "About"
};
this.getComponent = this.getComponent.bind(this);
}
getComponent(event) {
this.setState({ component: event.target.textContent })
}
render() {
const component = this.state.component;
let renderComponent = null; // declare a null variable that will contain the component
switch(component) {
case "Contact":
renderComponent = <ContactTab />;
break;
case "Quote":
renderComponent = <QuoteTab />;
break;
default:
renderComponent = <AboutTab />;
}
return (
<div>
<Sidenav>
<h1 className="navlink" onClick={this.getComponent}>
About
</h1>
<h1 className="navlink" onClick={this.getComponent}>
Quote
</h1>
<h1 className="navlink" onClick={this.getComponent}>
Schedule
</h1>
<h1 className="navlink" onClick={this.getComponent}>
Products
</h1>
</Sidenav>
{/* Use the variable here */}
{renderComponent}
</div>
);
}
}
export default App;
如果您的导航具有与文本不同的元素,那么它将无法工作。考虑使用提供组件名称参数的 onClick 函数:
<h1 className="navlink" onClick={() => this.getComponent('About')}>
{/* Won't work with the previous example, as it contains another html element */}
<i className='fa fa-info' /> About
</h1>
然后,在 getComponent
函数中:
getComponent(componentName) {
this.setState({ component: componentName })
}
还可以考虑为该函数提供一个更具描述性的名称,使其更容易理解它的作用(将组件名称设置为状态):
setViewComponentName(componentName) {
this.setState({ component: componentName })
}
关于javascript - 如何渲染不同的组件 onClick? (组件应替换为最新的单击处理程序。),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55408482/