Shadow DOM and ReactJS

后端 未结 1 495
陌清茗
陌清茗 2021-01-06 16:55

I am using web components in my application. And in a web component, I need to insert a react component. Web Component has Shadow DOM. When I try to render the react compone

相关标签:
1条回答
  • 2021-01-06 17:20

    If you want to insert it inside the shadow DOM of a web component, first select the component (e.g. with querySelector) and then its containing shadow (shadowRoot). Simplified example:

    // Create React Element.
    class Example extends React.Component {
      onClick() {
        console.log('Shadow!')
      }
      render() {
        return(
          <div onClick={this.onClick}>Hello World!</div>
        );
      }
    }
    
    // Create web component with target div inside it.
    const container = document.createElement('app');
    document.body.appendChild(container);
    
    // Add shadow root to component.
    const shadow = document.querySelector('app').createShadowRoot({ mode: 'open' });
    
    // Select the web component, then the shadowRoot.
    const target = document.querySelector('app').shadowRoot;
    
    ReactDOM.render(<Example />, target);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

    0 讨论(0)
提交回复
热议问题