我是ReactJS的新手,我正在尝试创建一个菜单,通过按下活动类将消失的任何功能,将出现新页面。例如,在这里,我试图点击我的订单并转发到我要求加载的页面。我该如何正确地做到这一点?这是我目前的代码:
import React from 'react';
import ReactDOM from 'react-dom';
import "./index.css";
class MainPanel extends React.Component {
render() {
return (
<div className="main-layout">
<header>
<ul className="top">
<h1>Header</h1>
</ul>
</header>
<ul className="categories">
<li>Main Panel</li>
<li onClick={<MyOrder />}>My Order</li>
<li>Technical Support</li>
<li>My Payments</li>
<li>Suggestions/ Questions</li>
</ul>
</div>
);
}
}
function MyOrder () {
return (
<div className="main-layout">
<header>
<ul className="top">
<h1>My Order</h1>
</ul>
</header>
<ul className="categories">
<li>Where is my order?</li>
<li>My order delays more than the expected time</li>
<li>My order status shows that the order arrived but it did not</li>
<li>I have a complaint</li>
<li>Suggestions/ Questions</li>
</ul>
</div>
);
}
ReactDOM.render(
<MainPanel />,
document.getElementById('root')
);
答案 0 :(得分:0)
如果没有React Router和其他第三方库,您可以这样做:
class Overview extends React.Component {
onMenuClick(id) {
return this.props.onMenuClick(id);
}
render() {
return(
<ul className="categories">
<li onClick={this.onMenuClick.bind(this, "mainPanel")}>Main Panel</li>
<li onClick={this.onMenuClick.bind(this, "myOrder")}>My Order</li>
<li onClick={this.onMenuClick.bind(this, "technicalSupport")}>Technical Support</li>
<li onClick={this.onMenuClick.bind(this, "myPayments")}>My Payments</li>
<li onClick={this.onMenuClick.bind(this, "suggestions")}>Suggestions/ Questions</li>
</ul>
);
}
}
class MainPanel extends React.Component {
// sets the initial value for this.state.page
componentWillMount() {
this.setState({
page: "overview"
});
}
switchPage(id) {
this.setState({ page: id });
}
showComponent() {
if(this.state.page === "overview") return (<Overview
onMenuClick={::this.switchPage}
/>);
if(this.state.page === "myOrder") return <MyOrder />;
throw new Error(`${this.state.page} is not a valid page id`);
}
render() {
return (
<div className="main-layout">
<header>
<ul className="top">
<h1>Header</h1>
</ul>
</header>
{ this.showComponent() }
</div>
);
}
}
您可以通过更新状态来更改视图。根据状态,安装/卸载不同的组件。
根据我的经验注意:尝试通过React Baobab或类似的东西(集中状态)处理你的应用状态(在我们的例子中是当前的页面信息),因为否则所有这些道具冒泡都会变得混乱。