【问题标题】:Is it possible to pass props from Link by React Router from a Component to the component by Link?是否可以通过 React Router 将来自 Link 的道具从组件传递到 Link 的组件?
【发布时间】:2017-07-12 08:56:44
【问题描述】:

这是我想从父组件主页做的代码:

class Home extends Component {
render() {
    const { environment } = this.props; // <-- this is the props I want to pass
    <Link environment to="/register"> // <-- this is what I want to do
     <RaisedButton label="Register" style={{ margin: 12 }} />
    </Link>
}

这是我的 React Router 配置代码:

ReactDOM.render(
   <BrowserRouter>
      <div>
      <Route exact path='/(index.html)?' component={Home}/>
      <Route  path='/register' component={Registration}/>
      </div>
    </BrowserRouter>,
  mountNode
);

我想将父组件 Home 中的一个 prop 传递给 Registration 组件,我该怎么做?

【问题讨论】:

  • Home 组件上有一个道具,我想将其传递给 Register。上面对我的场景示例进行了评论

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


【解决方案1】:

您可以像这样在 Link to 对象中传递一个状态:

 <Link to={{
  pathname: '/register',
  state: { linkState: this.props.myProp }
}}/>

然后在注册组件中,您可以像这样访问此状态:

this.props.location.state.linkState

欲了解更多信息,请参阅:https://reacttraining.com/react-router/web/api/Link

【讨论】:

  • 我试过这个但我有错误 Uncaught DOMException: Failed to execute 'pushState' on 'History'
猜你喜欢
  • 1970-01-01
  • 2015-07-18
  • 2019-12-05
  • 2019-08-11
  • 2018-01-17
  • 2018-12-17
  • 2018-02-28
  • 2019-12-01
  • 2021-07-31
相关资源
最近更新 更多