【发布时间】:2023-03-16 17:25:02
【问题描述】:
我有一个 onClick 功能可以导航到其他页面。我尝试了 this.props.history.push("/SecondPage/ID/") 和一些示例,但没有成功。
我有这样的组件:
export class MainPage extends Component {
constructor(props) {
super(props);
}
render(){
return (
<div id="main" onClick={this.NavigatetoOtherPage.bind(this)}>
)
}
NavigatetoOtherPage(){
let ID = this.props.ID; // I need to pass the ID as a parameter.
//Here I need to navigate to other page using. I can use window.location.href but I need to use react router.
}
}
export default connect(state => {
return {
ID: state.Reducer.ID,
};
})(MainPage)
我的 app.js 文件是这样的
export default class App extends Component {
render() {
return (
<Provider store={store}>
<Route exact path='/' component={MainPage}/>
<Route path='/SecondPage/:ID/' component = {SecondPage} />
</Provider>
);
}
}
我的 index.js 页面是这样的
export function renderPage() {
ReactDOM.render(
<Router>
<App />
</Router>
, document.getElementById('root'));
}
renderPage();
如何在没有 window.location.href 的情况下导航到第二页
【问题讨论】:
-
你有什么理由不使用 吗?
-
路由“/path”应该渲染什么?你的地址正确吗?
-
@İlker 我可以使用链接。但是我们如何在 OnClick 或 OnDoubleClick 中使用 Link?
-
@alisasani 路径是“/SecondPage/ID/”。
-
请提供更多细节。我根据您的代码在此处创建了一个沙盒链接 (codesandbox.io/s/react-router-forked-bf13w?file=/index.js),您可以看到它运行良好。
标签: reactjs react-router react-router-dom