1:使用withRouter()高阶函数 withRouter()高阶函数将注入 history 对象作为组件的 prop。该对象提供了push()和replace()方法,以避免使用上下文 import { withRouter } from 'react-router-dom' // this also works with 'react-router-native' const Button = withRouter(({ history }) => ( <button type='button' onClick={() => { history.push('/new-location') }} > {'Click Me!'} </button> ))
2:使用<Route>组件和渲染属性模式 <Route>组件传递与withRouter()相同的属性,因此您将能够通过 history 属性访问到操作历史记录的方法 import { Route } from 'react-router-dom' const Button = () => ( <Route render={({ history }) => ( <button type='button' onClick={() => { history.push('/new-location') }} > {'Click Me!'} </button> )} /> )
3:使用上下文 const Button = (props, context) => ( <button type='button' onClick={() => { context.history.push('/new-location') }} > {'Click Me!'} </button> ) Button.contextTypes = { history: React.PropTypes.shape({ push: React.PropTypes.func.isRequired }) }