React using react component inside of dangerouslySetInnerHTML

后端 未结 3 507
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 12:46

I have a question about using react. As you can see from the title, I\'m wondering if it is possible to use React component(that is created by React.createClass) inside of \

3条回答
  •  悲&欢浪女
    2021-01-12 13:12

    Old question but for future wonderers I think I might have a solution to this but do note that this will definitely break your redux flow if you're using it in your project.

    Basically, you should have some id in your dangerousSetInnerHTML text.
    The idea is to mount to that id in the componentDidMount lifecycle hook after your "dangerous HTML" has been mounted to DOM.

    e.g.

    const myStringHTML = `
      
    some text in my dangerous html
    `; const MySubComponent = React.createClass({ render() { return (

    MySubComponent

    ); } }); ... let myStringHTML; myStringHTML += "
      "; myStringHTML += "
    • "; myStringHTML += " "; myStringHTML += "
    • "; myStringHTML += "
    "; const MyComponent = React.createClass({ componentDidMount() { ReactDOM.render(, document.querySelector('#someid')); } render() { return (
    ); } });

    Do note that componentDidMount will however not be called on component updates. For more info on this refer to the lifecycle hook of react.

    Fair warning though that this does feel hacky and it is. This also has it's limitations as I mentioned some above but there can be time where you have no other option but to use dangerousSetInnerHTML and at times like this, this is an option. At other times do what @Rohit Singh Sengar suggested and try to do it in react.

提交回复
热议问题