react动态插入样式
这篇文章发表于 2023年10月29日,星期日,14:30
在开发组件过程中,偶尔需要动态的插入css,比如在在iframe中渲染组件后,iframe中是没有样式的,所以需要手动插入样式。
插入样式
通常是在useLayoutEffect中动态创建style
标签
useLayoutEffect(() => { if (!ref.current) { const style = document.createElement('style'); document.head.append(style); ref.current = style; } ref.current.innerText = css; return () => { if (ref.current) { document.head.removeChild(ref.current); ref.current = undefined; } }; }, [css]);
useStyle
useStyle使用一个动态插入style的hook,将上面的代码进行了封装,方便使用。
关于博主: 评论和私信会在第一时间回复
版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!