是否可以通过链接将React路由器中的道具从组件传递到组件?

时间:2017-07-12 08:56:45

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

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

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的支持我想要传递注册组件,我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以在链接to对象中传递状态,如下所示:

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

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

this.props.location.state.linkState

有关详细信息,请参阅:https://reacttraining.com/react-router/web/api/Link