如何从React将函数/事件处理程序传递给Web组件

时间:2019-09-19 13:30:13

标签: javascript reactjs web-component custom-element

我是Web组件的新手,正在尝试将Web组件与React集成。

在某些情况下,我必须将按钮从响应传递到Web组件。对于按钮的click事件,我附加了一个处理程序,该处理程序将在react中执行一些操作/操纵。因此必须将它从react传递到Web组件。

以下是示例代码:

反应成分:

import React, {Component} from 'react';

export class Sample extends Component {

    handleButtonOneClick = () => {
        alert(" ButtonOne Action happened, perform some action in React!!!!!!!!!!!");
    };
    handleButtonTwoClick = () => {
        alert("ButtonTwo Action happened, perform some action in React!!!!!!!!!!!");
    };

    render() {
        return (
                <my-sample-element >
                    <button id="button-one" onClick={this.handleButtonOneClick}> Button 1</button>
                    <button id="button-two" onClick={this.handleButtonTwoClick}> Button 2</button>
                </my-sample-element>
        );
    }
}

Web组件:

export class CustomSampleElement extends HTMLElement {

    constructor() {
        super();
    }

    connectedCallback() {
        const shadowDOM = this.attachShadow({mode: 'open'});
        const divElement = document.createElement('div');

        const childrenNode = this.children;
        while (childrenNode.length) {
            divElement.appendChild(childrenNode[0]);
        }

        shadowDOM.appendChild(divElement);
    }
}

customElements.define('my-sample-element', CustomSampleElement);

但是事件处理程序未添加到Web组件中。我不知道为什么您知道如何解决此问题吗?

0 个答案:

没有答案