Webcomponent自定义元素传函数onClick

Webcomponent Custom Element pass function onClick

我想使用 ReactJS 将函数传递给自定义元素

ReactJS 组件

import React from 'react';
import './SampleComponent';

export  class Button extends React.Component {

  handleClick = (event) => {
    console.log(event)
  }

  render() {

    return (
      <div>
        <sample-component onclick="handleClick"></sample-component>
      </div>
    )
  }
};

自定义元素

class SampleComponent extends HTMLElement {
  static get observedAttributes() {

  }

  // custom methods
  render() {
    this.innerHTML = `Custom Element`;
  }

  // lifecycle hooks
  connectedCallback() {
    this.render();
  }

}

window.customElements.define('sample-component', SampleComponent);

据我了解,当我传递 onclick 函数时 handleClick JS 将在自定义元素实现中搜索它(这就是我在控制台中收到错误的原因)。那么如何传递函数呢?我试过 "this.handle" 但还是没用。

由于反应 Documentation 你 html 应该看起来像这样

<sample-component onClick={handleClick}></sample-component>