使用react-shadow-dom-retarget-events不能完全解决问题
https://www.npmjs.com/package/react-shadow-dom-retarget-events
会有怪异的bug,比如组件里的点击事件只可以改state里某个属性的值一次,再点的话这个属性的值怎么也改不了
真正的解决方法
https://github.com/facebook/react/issues/9242#issuecomment-534096832
class CustomElement extends HTMLElement {
connectedCallback() {
// setup
const shadow = this.attachShadow({ mode: "open" });
const root = document.createElement("div");
shadow.appendChild(root);
// Making the shadow appear like document
// so react events work as normal
Object.defineProperty(root, "ownerDocument", { value: shadow });
shadow.createElement = (...args) => document.createElement(...args);
shadow.createElementNS = (...args) => document.createElementNS(...args);
shadow.createTextNode = (...args) => document.createTextNode(...args);
ReactDOM.render(<App />, root);
}
}
customElements.define("custom-element", CustomElement);
// DONT FORGET to add <custom-element></custom-element> to your page
网友评论