在React中为WebComponent加载自定义CSS的优雅方案求助
问题:在React中为WebComponent加载自定义CSS的优雅兼容方案
我需要将dzs-chip-selector模块中的自定义CSS文件加载到该模块定义的WebComponent中。
非React环境的可行方案
在非React环境下,直接在WebComponent标签内添加<link>子元素即可加载样式,代码如下:
<dzs-chip-selector ref={this.myRef} data-persistentOptions={JSON.stringify(this.chipSelectorOptions)}> <link rel="stylesheet" data-lazy-href="dzs-chip-selector/style/skins/skin-default.css"/> </dzs-chip-selector>
该方式可正常工作,但在React环境中失效——React渲染时不会将子元素传递给WebComponent引擎。
当前方案的缺陷
目前我采用弹出React脚本、通过ref异步加载CSS的方案,代码如下:
async function loadCss(){ import('chip-selector/dist/style/skins/skin-default.css').then((...args) => { const cssStyle = args[0].default[0][1]; $myRef.wrapper.insertAdjacentHTML('beforeBegin', `<style>${cssStyle}</style>`) }) }
这个方案虽能运行,但实现方式非常hacky,且在StackBlitz中会报错。我已尝试相关方案并参考过Shadow DOM样式相关内容,现寻求更优雅且兼容StackBlitz的解决方案。
内容的提问来源于stack exchange,提问作者digitalzoomstudio
相关产品推荐
相关产品推荐

