我有两个组件,我希望第一个组件是第二个组件中的呈现支柱,如果定义了第二个组件,它将封装第二个组件的内容。我不太明白如何写这个,我在渲染道具上找到的文档往往很难理解。有没有人写过类似的实现?
我想要的一般想法是,您可以在component1的component1道具中传递component2的道具,并在component2中使用它的道具来呈现<Component1>。
粗略代码示例,说明我正在尝试做什么(这不是要工作的)
interface Component1 {
id?: string;
children: React.ReactNode;
}
const Component1 = (props: Component1) => {
const { children } = props;
return (<div className="component1">{children}</div>)
}
interface Component2 {
component1?: (propsForComponent1) => <Component1 {...propsForComponent1}>
}
const Component2 = (props: Component2) => {
const {component1} = props;
if (component1) {
return {component1({id: 'exampleId', children: <div className="component2">Stuff for component 2</div>)}}
};
return (<div className="component2">Stuff for component 2</div>);
}编辑:已经改变了例子,因为意图是混淆人们。
编辑:现在将第一个组件作为支柱传递到第二个组件中。我认为一般的答案是不要尝试将组件作为两个组件使用,而只是将其应用于儿童。
发布于 2019-12-11 11:58:51
在代码示例中实际发生的情况是,即使您将整个组件(Component1)作为支柱传递,您也是而不是呈现它,而是使用导入的(或在范围内可访问的) Component1。
无论如何,你为什么要把一个完整的组件传递下来作为一个支柱,即使你基本上可以导入它呢?
我的建议是-使用一个道具,而不是一个组件,而是一个布尔标志,它决定组件是否应该被包装。
interface Component2 {
shouldBeWrapped?: boolean;
}
const Component2 = ({ shouldBeWrapped }: Component2) => {
if (shouldBeWrapped) {
return (
<Component1 with props given in on component1 property>
<div className="component2">Stuff for component 2</div>
</Component1>
);
}
return (<div className="component2">Stuff for component 2</div>);
}https://stackoverflow.com/questions/59285154
复制相似问题