简体   繁体   English

将道具从父状态传递给子组件-React Router

[英]Passing props to Children component from Parent state- React Router

One can pass props to a component of a child route (while using React Router) by passing the props to the Route component for the child component and accessing it in the child component of this route by this.props.route.propName . 通过将道具传递到子组件的Route组件,并通过this.props.route.propName在此路由的子组件中访问它,可以将道具传递到子路由的组件(使用React Router时)。

What about the props needed in a child component is a portion of the state of its parent component and not just some unrelated data to the components? 子组件所需的道具又是其父组件状态的一部分,而不仅仅是与组件无关的数据吗?

Since 以来

  • in <Router /> the state of a parent App is not in scope, one cannot pass it to component in a sub <Route /> , or <Router />中,父App的状态不在范围内,无法将其传递给子<Route /> ,或者

  • all reference to a child component in the parent component is {this.props.children} and not <aComponent data={this.state.somePortion} /> , one, again, cannot pass it through the syntax of expression {this.props.children} . 父组件中对子组件的所有引用都是{this.props.children}而不是<aComponent data={this.state.somePortion} /> ,同样,它不能通过表达式{this.props.children}

What is the catch? 有什么收获?

Update: Instead of store state within App , your state will need to be stored in the component that is rendering the routes then passed to the route. 更新:您的状态需要存储在呈现路线的组件中,而不是在App中存储状态,然后再传递给该路线。 You can use the method below to wrap the component if you want it to maintains it current propType list. 如果希望组件将其维护为当前propType列表,则可以使用以下方法包装该组件。

If you cannot use this.props.route.propName another option would be to use an High-Order Component (HOC) that wraps your component and use it on the route, then pass the route props to the component you want to render. 如果不能使用this.props.route.propName另一个选择是使用包裹组件的高阶组件(HOC)并在路线上使用它,然后将路线道具传递给要渲染的组件。

const WrappedComponent = ({route}) => {
  return (<Component data={route.data} />);
};

You could then further extensibility you could pass the component to render to the route as well. 然后,您可以进一步扩展,也可以将组件传递给路线。

<Route to='/about' component={WrappedComponent} data={[]} page={AboutPage} />

Then update wrapped to something like this: 然后将更新包装为以下内容:

const WrappedComponent = ({ route }) => {
   const { page:Component, ...rest } = route;
   return <Component {...rest} />;
};

This uses some ES2015+ with the rest operator, but would allow more reuse on this HOC. 它将ES2015 +与rest运算符一起使用,但将允许在此HOC上进行更多重用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM