javascript - 如何在 React JS 中将 HTML 字符串呈现给组件
问题描述
我有一个 HTML 内容作为例如的字符串<div>Hello</div>
,我只想在反应组件中将其呈现为 HTML,而不使用 innerHTML 方法,并且默认反应像危险的SetInnerHTML。让我知道是否有任何完美的替代方案可以有效地发挥作用。我只是不想使用任何像 html-to-react 这样的包。是否可以使用 React Render 中的任何其他默认方法来实现它?
export default class sampleHTML extends React.Component {
constructor(props) {
super(props);
this.state = {
currentState: "",
};
}
componentDidMount() {
this.setState({currentState :`<div>Hello</div>` });
}
render() {
return (
<div id="container">{this.state.currentState}</div>
)
};
};
我需要将标签呈现为字符串
解决方案
你可以在 react 中使用 dangerouslySetInnerHTML。有关更多详细信息,您可以使用以下链接: https ://reactjs.org/docs/dom-elements.html
export default class sampleHTML extends React.Component {
constructor(props) {
super(props);
this.state = {
currentState: "",
};
}
componentDidMount() {
this.setState({currentState: <div>Hello</div> });
}
this.createMarkup() {
return {__html: this.state.currentState};
}
render() {
return (
<div id="container" dangerouslySetInnerHTML={createMarkup()}></div>
)
};
};
推荐阅读
- spring-boot - Mybatis: IllegalArgumentException: Mapped Statements 集合不包含 xxx 的值
- javascript - bxSlider - 使用寻呼机时幻灯片之间的错误暂停
- c# - .equals() 和 == C# 的混淆?
- python - `multiprocessing` `starmap_async` 只调用一次回调?
- javascript - 如何仅在数组javascript中使用“forEach”函数列出项目
- rgraph - RGraph V5 升级 - 获取上下文时出错
- php - 使用迭代返回 for 循环的结果
- android - 为什么我的 android 选项卡布局不起作用?
- azure - 如何在 kubernetes 中从 Angular 应用程序调用 .net core web api
- algorithm - 装袋分类器(平均)如何工作?