如何在反应中动态构建组件道具

How to dynamically construct component props in react

我有一个动态构造道具的要求,对此结构有点困惑。请看下面的例子,children 表达式组件在这种情况下需要 parent 组件标题。

function SomeComponent(props){
   return <h1>{props.title}</h1>
}

import SomeComponent from 'someForm';

const contents = {
   title: 'hello',
   form: SomeComponent
}

另一个组件:

<Another data={contents}>

function Another(props){
  return (
     <Form title={props.data.title}>
      {props.data.form} => title should be passed to this component expression
      something like: <props.data.form title={props.data.title}>
      Is it possible or how to do this?
     </Form>
   );
}

实现此目标的最佳方法是什么? HOC 是一个选项,但问题到底是什么?

我希望我理解正确,我认为渲染道具模式是你最好的选择。 https://reactjs.org/docs/render-props.html

基本上在您的 <Form /> 组件中呈现 children 并将变量向下传递给 children

例如 render = () => this.props.children(this.props.title) 假设您在 <Form />

中有可用的道具

然后你选择在 <Form /> 中渲染哪个组件作为 child 以及使用什么道具

<Form>
  {(title) => <SomeComponent title={title}/>}
</Form>

title 只是为了这个例子,因为你正在传递 title props.. 在未来它可以被称为任何东西并且指代你传递给 children 的任何东西,它可以是道具、状态、特定处理程序等...

我可以通过动态构建道具而不需要 HOC 来满足我的要求,如下所示,这符合我的要求,但我不确定性能。

 const componentWithExtraProp = React.Children.map(form, (child) => {
    return React.cloneElement(child, {
      title: 'Testing...'
    });
  });