最难的部分是使用WithIcon 的规则我们只有一个吗?
我们只会在最左边吗?类似的东西。
但是,如果我们以您为榜样。对于WithIcon我们可以相对写这样的东西
const WithIcon = ({ i, children }) => {
return React.Children.map(children, (child) => {
return (
<>
<i className={`me-2 bi bi-${i}`}></i>
{React.cloneElement(child, { className: "with-icon" })}
</>
);
});
};
那么我们就可以随心所欲地使用它了
<WithIcon i="plus"><Button>Add item</Button></WithIcon>
我们所做的只是循环遍历子节点,这些子节点的反应是您放入其中的任何嵌套 jsx(在我们的例子中为按钮)
你可以在这里找到我的小提琴:https://codesandbox.io/s/react-font-awesome-forked-321tz?file=/src/index.js
更新
所以我之前的回答并没有完全达到我们想要的最终结果。遗嘱必须是主要父母
这个想法还是和之前的一样,但是这里我们在推断我们在 WithIcon 中传递的组件的类型这也增加了当我们在 WithIcon 中传递嵌套组件时的安全措施
const WithIcon = ({ i, children }) => {
return React.Children.map(children, (child) => {
const MyType = child.type; // So we can get the Button
return (
<MyType className="with-icon">
<i className={`me-2 bi bi-${i}`}></i>
{(React.cloneElement(child, {}), [child.props.children])}
</MyType>
);
});
};
我想我要睡觉了,我稍后会更新其余的解释。
在这里看小提琴:
https://codesandbox.io/s/react-font-awesome-forked-y43fx?file=/src/components/WithIcon.js
请注意,此代码不会保留传递组件的其他道具,但您可以通过在 MyComponent 处添加 {...child.props} 来相对添加它,这只是(反射之类的?)推断组件。
当然还有其他选项,例如 HOC Enhancers 来执行此操作,但这会增加您如何声明组件 api 的复杂性。所以选择最适合你的朋友