如何使用反应路由器导航到其他页面

时间:2021-03-12 20:07:25

标签: reactjs react-router react-router-dom

我有一个 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 的情况下导航到第二页

2 个答案:

答案 0 :(得分:1)

如果您使用的是 react-router-dom,您可以使用 useHistory 钩子或 Link 组件

import React from "react";
import { useHistory, Link } from "react-router-dom";

 // Then in your component
 const MainPage = (props) => {
  /**
   * hooks
   */
  const history = useHistory();

  /**
   * function
   */
  const handleNavigation = () => {
   let ID = props.ID; // I need to pass the ID as a parameter.
  
    history.push(`/dashboard/${ID}`)
  }

  return (
    <button id="main" onClick={() => history.push("/")}> Go to / </button>
    <button id="main" onClick={() => handleNavigation()}> Go to dynamic page 
    </button>
    <Link to={`/dashboard/${props.ID}`} className="some-styling">
      Using Link
    </Link>
  );
};

// I have merged both implementations



export default MainPage;

// 编辑:根据评论,问题是“历史没有出现在道具中。”

// Then you could use `withRouter` HOC, and then there will be 
// the `history` object in the wrapped component's props.

import {withRouter} from 'react-router-dom';


class MainPage extends React.Component {

  render(){
    console.log(this.props.history) // history object
    return(<div />)
  }
}

export default withRouter(MainPage)`

答案 1 :(得分:0)

写下一个小沙箱。我想这就是您想要实现的目标。

https://codesandbox.io/s/practical-tereshkova-ilbig?file=/src/App.js