Reactjs 导航到同一页面布局中的其他组件
我在屏幕左侧有一个数据列表,我正在使用map显示该列表,单击后,应在同一屏幕的右侧呈现一个新组件,并且url必须在浏览器中更改,考虑使用onClick而不是Link to,但如果使用,则无法指定url的更改Reactjs 导航到同一页面布局中的其他组件,reactjs,react-router,Reactjs,React Router,我在屏幕左侧有一个数据列表,我正在使用map显示该列表,单击后,应在同一屏幕的右侧呈现一个新组件,并且url必须在浏览器中更改,考虑使用onClick而不是Link to,但如果使用,则无法指定url的更改 const Home = (props) => { return( <div className="main-wrapper"> <div className="service-wrapper"> <Service/> </di
const Home = (props) => {
return(
<div className="main-wrapper">
<div className="service-wrapper">
<Service/>
</div>
<div className="list-wrapper">
<Route path="/service/service_name" exact component={List}/>
</div>
</div>
);
}
const Home=(道具)=>{
返回(
);
}
您可以使用onClick,但必须使用react路由器库提供的历史对象。
它将如下所示:-
onClick(() => history.push(`/service/${service}`));
要访问历史记录,您必须从react路由器库导入withRouter hoc
import { withRouter } from "react-router-dom";
class YourComponent extends Component {
const { history } = this.props;
}
export default withRouter(YourComponent);
左右仪表板结构应如下所示:-
const LeftDashboard = () => {
return (
<div>
// rest of your ui
</div>
)
}
const RightDashboard = ({ activeParam }) => {
const renderActive = () => {
switch(activeParam) {
case 1:
return somecomponent;
case 2:
return someother;
default:
return defaultcomponent;
}
}
return renderActive();
}
class App extends Component {
render() {
<React.Fragment>
<LeftDashboard />
<RightDashboard activeParam={//pass active param} />
</React.Fragment>
}
}
const LeftDashboard=()=>{
返回(
//用户界面的其余部分
)
}
常量RightDashboard=({activeParam})=>{
常量渲染=()=>{
开关(activeParam){
案例1:
返回组件;
案例2:
回报他人;
违约:
返回默认组件;
}
}
返回renderActive();
}
类应用程序扩展组件{
render(){
}
}
另一个选项是将路线放在右侧仪表板组件中:-
const RightDashboard = () => {
return (
<React.Fragment>
<Route path="/somepath" component={<Mycomponent />} />
<Route path="/someotherpath" component={<Myothercomponent />} />
</React.Fragment>
)
}
constRightDashboard=()=>{
返回(
)
}
结构的其余部分将保持与上面相同。React router v4利用动态路由,即如果位置匹配正确的路由,您的新组件可以渲染 要实现所需的功能,可以添加具有特定链接路径的路由,该路径将渲染新组件 在代码中,只需在以下行中进行更改:-
<div className="list-wrapper">
<Route path="Your path" component={List} />
</div>
它仍将转到下一页,而不是加载右侧的内容。当我单击左侧的任何一个元素时,请看,您必须准备一个包含左侧仪表板和右侧仪表板的布局。你必须在应用程序根目录中呈现它。现在,根据当前路线,您必须将活动参数传递到右侧仪表板,该仪表板将在左侧仪表板仍在的情况下呈现新组件。请检查更新的答案。这是实现这一点的几种方法之一。因此,我必须使用普通的链接,并使用onClick和history.push?否。您可以使用链接或onClick处理程序。那由你决定。标记不用于路由内部react。你可以使用onClick with history.push在一个常规div上。所以你的说法不是在app.js中定义我的路由,而是在这里定义(我的页面呈现的右侧)?不,保持这些路由在app.js中的状态。只需在此处添加另一个。是的,尝试过,但它仍然会被路由到下一页,我的结构如下:首先,我有我的app.js,当有一个按钮,单击后转到服务,其中列出了服务,并单击左侧的任何一个服务,它被路由到列表组件,并应在右侧呈现。更新后,My Home.js由服务和列表组成,服务位于左侧,在我使用链接的服务内部,因此当单击时,它将转到列表组件,根据路由,列表组件应在右侧呈现。