例如,我如何在此代码段中实现 addStyles
函数
const addStyles = // ...
const Element = ({ children }) => (
<div>{children.map(addStyles)}</div>
);
谢谢
最佳答案
使用React.Children.map
Facebook 提供的功能。
Invokes a function on every immediate child contained within children with this set to thisArg. If children is a keyed fragment or array it will be traversed: the function will never be passed the container objects. If children is null or undefined, returns null or undefined rather than an array.
然后使用 React.cloneElement
返回具有适当样式的每个子项的克隆。这将浅层合并第二个参数中对象中提供的任何属性。您可以使用它来覆盖子项的当前样式。如果您愿意,您可以提供 { className: "newClassName"}
作为第二个参数。
const StylishComponent = ({ children }) => {
const iLikeBlueStyles = { color: "blue" };
const clones = React.Children.map(children, child => {
return React.cloneElement(child, { style: iLikeBlueStyles });
});
return (
<div>
{clones}
</div>
);
};
关于reactjs - 如何为元素的所有子元素添加样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45682544/