是否可以通过 React 路由器将 Link 中的 props 从组件传递到通过 Link 传递组件?



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

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>
}

这是我的反应路由器配置代码:

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

有一个来自父组件 Home 的道具,我想传递给注册组件,我该怎么做?

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

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

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

this.props.location.state.linkState

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

最新更新