我知道这是一种糟糕的做法,但对于这种情况来说,这是最好的解决方案。我收到了来自服务器的响应,如下所示:
<style id="styles">.color_txt{color:green;}</style>我正尝试在head标记中添加:
 let styleEl = new DOMParser().parseFromString(res.data.html, "text/xml");
 styleEl.type= "text/css";
 // Remove current style
 document.getElementById('styles').remove();
 document.getElementsByTagName('head')[0].appendChild(styleEl.documentElement);我看到新样式被附加到head标记中,但问题是该样式并未应用,而是从元素中删除。我正在使用React。
//编辑
如果我通过web控制台在新创建的style标签中手动添加样式,它也不适用。
发布于 2019-02-03 08:14:17
这里有一个库可以做到这一点:https://www.npmjs.com/package/react-style-tag
下面是你如何使用它:
import React, { Component } from "react"; 
import { Style } from "react-style-tag";
class App extends Component {
  constructor(props) {
     super(props);
     this.state = { styleTag: false };
     fetchStyleTag().then(styleTag => {
        this.setState({ styleTag });
     });
  }
  render() {
    const { styleTag } = this.state;
    return styleTag && <Style>{ styleTag }</Style>;
  }
}https://stackoverflow.com/questions/54498751
复制相似问题