// 定义创建style并插入css的方法
function setInlineStyle(css: string, id="inline-style") {
// 如果相同的样式已存在,则不创建
if (!document.getElementById(id)) {
let style:any = document.createElement(‘style‘);
style.setAttribute("id", id)
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
document.getElementsByTagName(‘head‘)[0].appendChild(style);
}
}
// 定义删除style的方法
function removeInlineStyle( id="inline-style") {
let element = document.getElementById(id);
if (element) {
element.remove();
}
}
// 组件中使用方式(typescript+hooks)
const css = `.specific-jobCard-default-btn{border-color:${props.btnColor};color:${props.btnColor}} .specific-jobCard-default-btn:hover{background-color:${props.btnColor}}`;
useEffect(()=>{
setInlineStyle(css, "specific-jobCard");
return () => removeInlineStyle("specific-jobCard");
});
原文:https://www.cnblogs.com/shellon/p/13643862.html