(我正在开发一个本机项目)
我有一个自定义组件,它将另一个自定义组件作为其支持:
<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
传入optionalComponent
的car
道具?(知道它总是有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>
);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句