gpt4 book ai didi

javascript - 影子 DOM 和 ReactJS

转载 作者:行者123 更新时间:2023-11-29 23:53:22 27 4
gpt4 key购买 nike

我在我的应用程序中使用网络组件。在 Web 组件中,我需要插入一个 React 组件。 Web Component 有 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

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

最佳答案

如果你想将它插入到网络组件的影子 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>

关于javascript - 影子 DOM 和 ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42274721/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com