Click event not firing when React Component in a Shadow DOM

前端 未结 4 1434
耶瑟儿~
耶瑟儿~ 2020-12-08 10:23

I have a special case where I need to encapsulate a React Component with a Web Component. The setup seems very straight forward. Here is the React Code:

//         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 11:16

    I fixed a bug cleaned up the code of @josephvnu's accepted answer. I published it as an npm package here: https://www.npmjs.com/package/react-shadow-dom-retarget-events

    Usage goes as follows

    Install

    yarn add react-shadow-dom-retarget-events or

    npm install react-shadow-dom-retarget-events --save

    Use

    import retargetEvents and call it on the shadowDom

    import retargetEvents from 'react-shadow-dom-retarget-events';
    
    class App extends React.Component {
      render() {
        return (
            
    alert('I have been clicked')}>Click me
    ); } } const proto = Object.create(HTMLElement.prototype, { attachedCallback: { value: function() { const mountPoint = document.createElement('span'); const shadowRoot = this.createShadowRoot(); shadowRoot.appendChild(mountPoint); ReactDOM.render(, mountPoint); retargetEvents(shadowRoot); } } }); document.registerElement('my-custom-element', {prototype: proto});

    For reference, this is the full sourcecode of the fix https://github.com/LukasBombach/react-shadow-dom-retarget-events/blob/master/index.js

提交回复
热议问题