应避免通过道具传递零件类型

时间:2019-12-23 10:52:08

标签: reactjs react-native

在编码时,我觉得实现以下内容最为方便,即使我知道render props也可以做到。

const Parent = ({Child1:ComponentTyp<Props1>,Child2:ComponentTyp<Props2>})=>{
     const someProps1:Prop1 = {...};
     const someProps2:Prop2 = {...};

     return (<>
               <Child1 ...someProps1/>
               <SomeOtherComponent></SomeOtherComponent>
               <Child2 ...someProps/>
            </>)
}

const Componenet1 = ()=><Parent Child1={Componenet1_Child1} Child2={Componenet2_Child2} />;
const Componenet2 = ()=><Parent Child1={Componenet2_Child1} Child2={Componenet2_Child2} />;
`Componenet1_Child1` and `Componenet2_Child1` have the same props(Props1).
`Componenet1_Child2` and `Componenet2_Child2` have the same props(Props2).

但这似乎不好。 我应该避免执行上述操作,为什么?

除了优雅,我找不到真正的原因。

1 个答案:

答案 0 :(得分:0)

从某种意义上讲,您的方法是“渲染道具”。 我可以想到的处理香草“渲染道具”的好处是,您可以安全地在作为道具传递的函数中使用钩子。

您认为方法的缺点(但它也适用于“渲染道具”)是,比简单的构成更难理解,因此除非someProps取决于{ {1}}最好让他们成为孩子。

Parent

播放代码here

您可能考虑阅读的另一个主题是higher order components

相关问题