在组件卸载时删除导入的样式



我遇到了一个问题在我的React某个组件需要动态加载样式表的应用程序(当组件被加载时,它被加载;当它被卸载时,它将从页面中删除)。

令我惊讶的是,我似乎找不到任何关于动态加载的样式表在线或在官方的React文档。我找到的最接近的解决方案是2017年的这个答案,虽然这个解决方案适用于挂载组件,但它不会在卸载后删除样式表。

总有一些变通方法,比如在组件挂载后,在头部添加来自我的CDN的样式表,但我想在一个目录中保留尽可能多的css。

理想的解决方案是这样的:

class Parent extends React.Component{
render(){
return <div></div>;
}
}
export default withStyles(Parent, [pathToStylesheet]);
// or... 
class Parent extends React.Component{
componentDidMount(){ import(pathToCss); }
componentWillUnmount(){ removeImport(pathToCss); }

render(){
return <div></div>;
}
}

感谢所有的帮助,干杯。

import React, { Component } from "react";
import styleAsString from '!!raw-loader!../styles/MyComponent.css';
class MyComponent extends Component {
componentDidMount() {
this.addStyle(styleAsString);
}
componentWillUnmount() {
if(this.style) {
document.head.removeChild(this.style);
}
}
addStyle = (content) => {
const style = document.createElement("style");
style.type= "text/css";
style.innerHTML = content;
this.style = document.head.appendChild(style);
};
render() {
return <div> textInComponent </div>;
}
}

导入css文件为字符串,加载&手动卸载CSS样式;只是一个想法,没有经过测试!

最新更新