【问题标题】:Shadow DOM and ReactJS影子 DOM 和 ReactJS
【发布时间】:2017-07-05 14:38:05
【问题描述】:

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

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 中呈现?

【问题讨论】:

  • 即使它使用 Shadow DOM,您也可以获取生成的 HTML 并将其加载到那里,还是我在这里遗漏了什么?
  • 什么是“app1”?你不是说"#app1"吗?
  • @Supersharp 这是一个网络组件。
  • no..它是 div#app1...我的错..它基本上在 shadowDOM 中
  • 你见过this吗?这是 Web 组件和 React 组件如何互操作的示例

标签: javascript reactjs shadow-dom


【解决方案1】:

如果你想将它插入到 web 组件的 shadow DOM 中,首先选择组件(例如 querySelector),然后选择它包含的影子(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>

【讨论】:

  • 问题是react 无法执行所有操作,例如单击不起作用。而且可能有组件的多个实例,这样我需要调用每个地方
  • onClick 为我工作,更新了我的答案。 “呼叫每个地方”是什么意思?你每次都必须用ReactDOM渲染它?
  • 谢谢。发现我犯了一个小错误。我的 DOM 在阴影中下降了 2 级,并且仅在一处提到了 slot 元素
【解决方案2】:

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

// 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 类比钩子等效项工作得更好
  • innerHTML 的东西有点老套,状态更新不适用于此组件

【讨论】:

    猜你喜欢
    • 2015-09-14
    • 2019-08-01
    • 2015-07-10
    • 2018-08-27
    • 2018-08-19
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多