问题
I have this Router in my App.js:
<Router basename={process.env.REACT_APP_ROUTER_BASE || '/MyApp'}>
<Switch>
<Route path="/" exact component={HomePage} />
<Route path="/login" component={Login} />
<Route path="/editProject" /*render={(props) => <ProjectEdit {...props} history={props.history} />}*/ component={ProjectEdit} />
{/*<Redirect path="*" to="/" />*/}
</Switch>
</Router>
From HomePage component I'm using < ProjectsList> component which have < Project> components. Within the < Project> component I have an option of the menu for Editing a project and I'm trying to use there:
<OverflowMenuItem itemText="Edit" href="#" onClick={ () => this.props.history.push('/editProject')}/>
But I'm getting that props is undefined!
Resolution:
I passed the props.history as a prop history= {this.props.history} in this order:
HomePage -> ProjectsList -> Project
回答1:
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);
来源:https://stackoverflow.com/questions/59453964/react-pass-history-to-a-component-defined-in-the-router