程序开发 · 2024年5月2日

React 嵌套组件的 CSS 修饰会影响内部组件吗?

嵌套组件的 修饰会不会影响内部组件?

如果你有一个像下面这样嵌套的 react 组件:

<componenta>
  <componentb>
  </componentb>
</componenta>

登录后复制

那么,对 componenta 设置 css 属性是否会渗透到 componentb 中呢?

答案是:不会

立即学习“”;

react 使用 css 模块和 css-in-js 等技术来防止 css 渗透。这些技术通过生成随机字符串来为每个组件创建唯一的 css 规则。因此,对 componenta 施加的 css 属性将不会影响 componentb 的样式。

请参阅代码示例,其中 componenta 具有一个红色边框,而 componentb 具有一个蓝色背景:

const componenta = styled.div`
  border: 1px solid red;
`;

const componentb = styled.div`
  background-color: blue;
`;

reactdom.render(
  <componenta>
    <componentb>hello world</componentb>
  </componenta>,
  document.getelementbyid('root')
);

登录后复制

输出:

<div style="border: 1px solid red;">
  <div style="background-color: blue;">Hello World</div>
</div>

登录后复制

如你所见,componentb 的蓝色背景不受 componenta 红色边框的影响。

以上就是React 嵌套组件的 CSS 修饰会影响内部组件吗?的详细内容,更多请关注GTHOST其它相关文章!