影子 DOM 和 ReactJS [英] Shadow DOM and ReactJS

查看:82
本文介绍了影子 DOM 和 ReactJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中使用 Web 组件.在 web 组件中,我需要插入一个 react 组件.Web 组件具有 Shadow DOM.当我尝试使用以下方法渲染 react 组件时出现错误.

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'));

错误

target container is not a dom element

我尝试使用 Web 组件 API 的 content 但随后它被渲染在组件顶部而不是内部.任何线索如何使 React 组件在 shadow DOM 中呈现?

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?

推荐答案

如果你想把它插入到一个 web 组件的 shadow DOM 中,首先选择该组件(例如使用 querySelector)然后它包含的阴影(shadowRoot).简化示例:

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').attachShadow({ 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>

这篇关于影子 DOM 和 ReactJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆