Shadow DOM and ReactJS

安稳与你 提交于 2020-01-15 06:14:45

问题


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 component using following I get the error.

comp = React.createElement(ReactElem, {
    config: config,
    onRender: handleRender
});

ReactDOM.render(comp , self.shadowRoot.querySelector('#app1'));

Error

target container is not a dom element

I tried to use content of Web component API but then it gets rendered on top rather inside component. Any leads how can make React component to get rendered inside shadow DOM?


回答1:


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>


来源:https://stackoverflow.com/questions/42274721/shadow-dom-and-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!