在 React Component 中为 TSX 标签使用事件处理程序

Make use of event handler in React Component for TSX tag

有没有办法让 React 组件中定义的事件处理程序可以在类似 HTML 的标签中访问?我的意思是:

<MyComp param1="abc" param2="def" onDoSomething={this.someMethod} />

我的目标是定义onDoSomething,但目前我只知道如何创建参数,例如param1param2

export interface MyCompProps {
    param1: string;
    param2: string;
}

export interface DoSomethingEvent {
    someParam: string;
}

export class MyComp extends React.Component<MyCompProps, {}> {
    private doSomethingDispatcher = new EventDispatcher<DoSomethingEvent>();

    public onDoSomething(handler: Handler<DoSomethingEvent>) {
        this.doSomethingDispatcher.register(handler);
    }

    private fireDoSomething(param: string) {
        this.doSomethingDispatcher.fire({someParam: param});
    }
}

如何使事件处理程序 onDoSomething 可通过 TSX 访问,类似于使用 onClick 事件?

您可能 运行 遇到问题,因为您当前没有为 onDoSomething 提供函数,但返回的结果:

<MyComp param1="abc" param2="def" onDoSomething={this.someMethod()} />

应该是

<MyComp param1="abc" param2="def" onDoSomething={this.someMethod} />