[英]How to pass props to a component passed as props in React?
I want to pass props to a component that is passed as props like this:我想将道具传递给作为道具传递的组件,如下所示:
<Field
name="persons"
component={Persons}
/>
I've tried this but it didn't work:我试过这个,但没有用:
component={<Person prop={prop} />}
How can I make this work?我怎样才能使这项工作?
you can pass the component type and props in two different properties您可以在两个不同的属性中传递组件类型和道具
<Foo component={Bar} componentProps={...} />
then in Foo
component, you do this然后在
Foo
组件中,您执行此操作
render() {
const Component = this.props.component;
const props = this.props.componentProps;
return <div> ... <Component {...props}/> ...</div>
}
or you can pass a function that renders you component like this或者你可以传递一个函数来呈现你这样的组件
<Foo component={() => <Bar props />}/>
then in Foo
component, you do this然后在
Foo
组件中,您执行此操作
render() {
return <div> ... {this.props.component()} ...</div>
}
or you can do as you suggested in the question like this或者你可以按照你在这个问题中的建议做
<Foo component={<Bar props/>}/>
then in Foo
component, you do this然后在
Foo
组件中,您执行此操作
render() {
return <div> ... {this.props.component} ...</div>
}
its all depend on how you will use the passed component in Foo
component, or in your case the Field
component这完全取决于您将如何使用
Foo
组件中传递的组件,或者在您的情况下是Field
组件
a component is nothing more than a function that returns a react component.组件只不过是一个返回反应组件的函数。 when you do
<Person prop={prop} />
you are actually invoking that function in jsx style.当您执行
<Person prop={prop} />
您实际上是在以 jsx 样式调用该函数。
Therefore, you need to wrap your Person
component into another function that returns Person
like:因此,您需要将
Person
组件包装到另一个返回Person
函数中,例如:
// props here is in case <Field> pass some props to component
component={(props) => <Person {...props} prop={prop} />}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.