
嵌套组件的 css 修饰会不会影响内部组件?
如果你有一个像下面这样嵌套的 react 组件:
那么,对 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(, document.getelementbyid('root') ); hello world
输出:
Hello World
如你所见,componentb 的蓝色背景不受 componenta 红色边框的影响。










