首页 > 解决方案 > 如何在 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>
        )
    };
};

示例链接

我需要将标签呈现为字符串

标签: javascripthtmlreactjsreact-reduxrender

解决方案


你可以在 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>
        )
    };
};

推荐阅读