美文网首页
解决shadow dom react点击事件失效

解决shadow dom react点击事件失效

作者: 此昵称已被狗抢占 | 来源:发表于2019-11-01 20:08 被阅读0次
    使用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
    

    相关文章

      网友评论

          本文标题:解决shadow dom react点击事件失效

          本文链接:https://www.haomeiwen.com/subject/cquqbctx.html