将值设置为作为其父组件的另一个道具传入的组件的道具

set a value to a prop of a component that is passed in as another prop of its parent component

(我正在开发一个react-native项目)

我有一个自定义组件,它使用另一个自定义组件作为其属性:

<MyCustomComponent
        data={mydata}
        optionalComponent={<MySubComponent />}
      />

MySubComponent 看起来像这样:

const MySubComponent = ({car}) => {
   ...
}
export default MySubComponent;

正如你在上面看到的,这个组件有一个 car 属性。

MyCustomComponent 看起来像这样:

const MyCustomComponent = ({data, optionalComponent}) => {
   const myCar = getCar();
   // How can I set myCar to optionalComponent passed in here??
}
export default MyCustomComponent;

我的问题是 MyCustomComponent,我如何将 myCar 设置为传入的 optionalComponentcar 属性? (知道它总是有一个 car 道具)。

(请不要建议将 myCar 移动到更高级别然后正常情况下通过。我想知道我的问题是问的可能性。)

像这样将组件的引用传递给自定义组件:

<MyCustomComponent data={mydata} optionalComponent={MySubComponent} />

并重新分配对大写变量的引用:

const MyCustomComponent = ({ data, optionalComponent }) => {
   const MyCar= optionalComponent;
   // ..
   return <MyCar /* Add the required props here */ />
}

或者,您可以利用 children 道具,但您必须将 MySubComponent 包裹在 MyCustomComponent 内,如下所示:

<MyCustomComponent data={mydata}>
  <MySubComponent /* Add the required props here */ />
</MyCustomComponent>

并且在 MyCustomComponent 中:

const MyCustomComponent = ({ data, children }) => {
   // ..
   return (
     <div>
       {/** other stuff */}
       {children}
       {/** other stuff */}
     </div>
   );
}

如果我理解你想要的是正确的,那么我认为你是在倒退。传入的组件实际上没有任何 props,它只是在被调用但尚未被调用时才接受 props。如果您希望两个组件都使用相同的汽车道具,那么为什么不将其传递给 MyCustomComponent 并让该组件将其传递给 MySubComponent?这是正常的反应流程。或者,您可以使用上下文 API 并将两个组件存储并连接到同一个存储区,但不清楚您为什么要这样做。

MyCustomComponent 是实际呈现 MySubComponent 实例的组件吗?您要获取其汽车道具?