【问题标题】:How to dynamically construct component props in reactreact中如何动态构造组件props
【发布时间】:2021-04-03 09:09:55
【问题描述】:

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

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 是一个选项,但问题到底是什么?

【问题讨论】:

    标签: reactjs higher-order-components


    【解决方案1】:

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

    基本上在您的 &lt;Form /&gt; 组件中渲染 children 并将变量传递给子级

    例如 render = () =&gt; this.props.children(this.props.title) 假设您在&lt;Form /&gt; 中有可用的道具

    然后你选择要在 &lt;Form /&gt; 中作为孩子渲染的组件以及使用什么道具

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

    title 仅用于此示例,因为您正在传递标题道具.. 将来它可以被称为任何东西,并指代您传递给孩子的任何东西,它可以是道具、状态、特定处理程序等.. .

    【讨论】:

    • somecomponent不能像这里的泛型一样使用,它作为表达式组件{SomeComponent}传递出去
    • @MithunShreevatsa 很公平,这是我制作的一个简单示例,它显示了一个快速的基本渲染道具,取决于你想抽象多远,你也可以制作一个 HOC包装codesandbox.io/s/smoosh-water-61jip?file=/src/App.js
    • 努力工作,感谢您的时间和知识,一切顺利。坚持下去
    【解决方案2】:

    我能够通过动态构建道具而不需要 HOC 来按照我的要求管理它,这符合我的要求,但我不确定性能。

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

    【讨论】:

      猜你喜欢
      • 2019-06-08
      • 1970-01-01
      • 2021-11-11
      • 2018-05-06
      • 1970-01-01
      • 2018-03-10
      • 2018-11-23
      • 2019-06-14
      • 2021-06-16
      相关资源
      最近更新 更多