我正在使用react-sidenav程序包根据所单击的内容浏览不同的组件。但是,当我尝试实现此功能时,此方法不起作用。这是我的SideNav
组件:
import React from 'react';
import SideNav, { Nav, NavIcon, NavText } from 'react-sidenav';
import { BrowserRouter as Router, Route, Redirect} from 'react-router-dom';
//specify the base color/background of the parent container if needed
const MySideNav = () => {
return (
<div style={{background: '#2c3e50', color: '#FFF', width: 200}}>
<SideNav highlightColor='#E91E63' highlightBgColor='#00bcd4' defaultSelected='pos' onItemSelection={ (id, parent) => {
<Router>
<Redirect push to={`/${id}`} />
</Router>
}}>
<Nav id='home'>
<NavText>Home</NavText>
</Nav>
<Nav id='about'>
<NavText>About</NavText>
</Nav>
</SideNav>
</div>
)
}
export default MySideNav;
我在Routes.js
文件中也有此文件,该文件在App.js
中渲染:
<main>
<Switch>
<Route exact path="/home" component={Home} />
<Route path="/about" exact component={About} />
</Switch>
</main>
然后,我有单独的About.js
和Home.js
组件,我已经在Routes.js
中导入了它们。单击侧边栏中的单个项目时,无法重定向到任何其他组件。
因为我是React的初学者,所以我无法弄清楚哪里出了问题。有人可以帮我吗?那将不胜感激!
更新
使用withRR4
时,重定向在URL栏中完成,但未呈现目标组件。这是我的代码:
import React from 'react';
import { Nav, withRR4 , NavIcon, NavText } from 'react-sidenav';
import { BrowserRouter as Router, Route, Redirect} from 'react-router-dom';
const SideNav = withRR4();
//specify the base color/background of the parent container if needed
const MySideNav = () => {
return (
<div style={{background: '#2c3e50', color: '#FFF', width: 200}}>
<Router>
<SideNav highlightColor='#E91E63' highlightBgColor='#00bcd4'>
<Nav id='home'>
<NavText>Home</NavText>
</Nav>
<Nav id='about'>
<NavText>About</NavText>
</Nav>
</SideNav>
</div>
)
}
export default MySideNav;
答案 0 :(得分:1)
您需要按照文档中的说明使用withRR4: https://www.npmjs.com/package/react-sidenav#react-router-4-integration
编辑
您需要在<Route/>
<Router />
import React from 'react';
import { withRR4, Nav, NavText } from 'react-sidenav';
import { BrowserRouter as Router, Route } from 'react-router-dom';
const SideNav = withRR4();
class MySideNav extends React.Component {
renderHome = () => {
return <div>Home</div>;
};
renderAbout = () => {
return <div>About</div>;
};
render() {
return (
<Router>
<div style={{ background: '#2c3e50', color: '#FFF', width: 200 }}>
<SideNav default='home' highlightColor='#E91E63' highlightBgColor='#00bcd4'>
<Nav id='home'>
<NavText> Home </NavText>
</Nav>
<Nav id='about'>
<NavText> About </NavText>
</Nav>
</SideNav>
</div>
<div style={{ padding: 20 }}>
<Route exact path="/" render={this.renderHome}/>
<Route path="/home" render={this.renderHome}/>
<Route path="/about" render={this.renderAbout}/>
</div>
</Router>
);
}
}