我有一个 React 组件,它接收一个 prop codeBlock
,然后将其存储在组件的状态中。
其结构如下:
codeBlock = {
code: `<div></div>`,
language: 'html'
}
我想将这个 codeBlock.code
(模板文字字符串)转换为 html 元素,这样当我在渲染元素时添加/附加它时,我将得到 DOM 元素而不是文字字符串。
到目前为止我尝试过的事情,
在componentDidMount()
中,我尝试了两种不同的方法:-
- 使用 DOMParser:
componentDidMount() {
const parser = new DOMParser();
const output = parser.parseFromString(this.state.codeBlock.code, 'text/html');
this.setState({
output
});
}
此方法不起作用并引发此错误: 对象作为 react 子项无效(发现:[object htmldocument])
- 使用 String.raw:
componentDidMount() {
this.setState({
output: String.raw `${this.state.codeBlock.code}`
});
}
此方法按原样打印模板字符串,并且不创建任何元素。
在下面的代码部分中,它应该呈现为 html 元素而不是字符串。
最佳答案
您可以使用innerHTML
。
HTML:
<div id="elem"></div>
JS:
const codeBlock = {
code: `<div class="container"></div>`,
language: 'html'
}
const elem = document.getElementById("elem");
elem.innerHTML = codeBlock.code;
关于javascript - 将模板文字转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64848019/