影子 DOM 和 ReactJS

IT技术 javascript reactjs shadow-dom
2021-05-14 14:03:36

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

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

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

错误

target container is not a dom element

我尝试使用contentWeb 组件 API,但随后它在组件顶部而不是内部呈现。任何线索如何使 React 组件在 shadow DOM 中呈现?

2个回答

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

// 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>

嘿,我的朋友,我花时间为我们制作了这个:

// ShadowRoot.js

import React from "react";

export class ShadowRoot extends React.Component {

    attachShadow(host) {
        if (host == null) {
            return;
        }
        host.attachShadow({mode: "open"});
        host.shadowRoot.innerHTML = host.innerHTML;
        host.innerHTML = "";
    }

    render() {
        return (
            <span ref={this.attachShadow}>
                {this.props.children}
            </span>
        );
    }

}

像这样使用它:

<ShadowRoot>
    // put stuff here you want inside shadow root
</ShadowRoot>

需要考虑的2件事:

  • 该课程React.Component的效果比 hook 等效
  • innerHTML事情是有点哈克,并且状态更新不与该组件工作