我知道这根本不是什么好做法,但这是针对这种情况的最佳解决方案。 我收到了服务器的响应,如下所示:
<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
。
//编辑
如果我通过网络控制台在新创建的样式标签中手动添加样式,它也不适用。
最佳答案
这里有一个库可以做到这一点: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>;
}
}
关于javascript - 获取响应 <style> 标签并使用 React 将其附加到 head HTML 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54498751/