我有一个问题,我不确定是否可以。 这是示例代码。 我有一个组件,我希望每次他们使用我的组件和一个孩子时 它应该只接受特定的组件。
例如:
<tableComponent>
<tableHeaderComponent/>
<tableHeaderComponent/>
<tableHeaderComponent/>
</tableComponent>
but for this type it should not be accepted
<tableComponent>
<th>blah</th>
<th>blah2</th>
<yourowncomponent/>
</tableComponent>
谢谢, 乒乓球
答案 0 :(得分:1)
向您要允许的组件分配displayName
,并在父组件内部检查子代是否具有允许的displayName
const Good = () => <h1>Good</h1>;
Good.displayName = "Good";
const Bad = () => <h1>Bad</h1>;
const WithGoodOnly = ({ children }) => {
let allowed;
if (Array.isArray(children)) {
allowed = children.every(child => child.type.displayName === "Good");
} else {
allowed = children.type.displayName === "Good";
}
return allowed ? <div>{children}</div> : null;
};
渲染
const App = () => (
<WithGoodOnly>
<Good />
</WithGoodOnly>
);
渲染
const App = () => (
<WithGoodOnly>
<Good />
<Good />
</WithGoodOnly>
);
未呈现
const App = () => (
<WithGoodOnly>
<Good />
<Bad />
</WithGoodOnly>
);