React Pass history to a component defined in the Router

前端 未结 1 1039
一向
一向 2021-01-26 13:43

I have this Router in my App.js:


                
                    <         


        
相关标签:
1条回答
  • 2021-01-26 14:04

    If you are working with a Functional Component, you can simply access the history instance object within your component using the useHistory hook, as stated on the React-Router documentation.

    import { useHistory } from 'react-router-dom';
    
    
    function HomeButton() {
      let history = useHistory();
    
      function handleClick() {
        history.push("/home");
      }
    
      return (
        <button type="button" onClick={handleClick}>
          Go home
        </button>
      );
    }
    

    If you are working with a Class Component, you can wrap your component with withRouter, and then access the history object within your component

    import { withRouter } from 'react-router';
    
    class YourComponent extends React.Component {
    
      render() {
        const { history } = this.props;
    
        return <OverflowMenuItem itemText="Edit" href="#" onClick={ () => history.push('/editProject')}/>;
      }
    }
    
    export default withRouter(YourComponent);
    
    0 讨论(0)
提交回复
热议问题