reactjs - 如何为元素的所有子元素添加样式

标签 reactjs styled-components

例如,我如何在此代码段中实现 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/

相关文章:

javascript - React, styled-components - 在导入的样式 div 上设置 props

node.js - 获取 "blocked by CORS policy: No ' Access-Control-Allow-Origin' header 存在于请求的资源上。”使用 Axios 的 MERN 堆栈

Css 菜单项/最佳方式 li 和一个或按钮

reactjs - 样式组件警告建议我使用 `attrs` 方法,即使我是?

javascript - 在 react 中显示/隐藏特定的 <div>

styled-components - innerRef 被完全忽略

css - 容器问题 - React 和样式化组件

html - 如何确保访问的链接不会在 react 时变成紫色?

javascript - 在运行被调用的函数之前触发一个函数运行

javascript - React hooks - setState 不更新状态属性