嵌套组件的 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 修饰会影响内部组件吗?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号