Reactjs 如何公开';通用';来自TypeScript v2.x中自定义React组件的事件

Reactjs 如何公开';通用';来自TypeScript v2.x中自定义React组件的事件,reactjs,events,typescript,definitelytyped,Reactjs,Events,Typescript,Definitelytyped,当我们仍然将Typescript 1.8.x与当时React的(明确键入的)类型描述文件结合使用时,我们使用“事件”类型在React组件属性中声明“通用”事件。然后,我们可以将该属性(being和event handler函数)的值附加到例如HtmlInputElement的“onChange”属性上 interface IIcoonProps { onClick?: Event; } interface IIcoonDetails { cssClass: string;

当我们仍然将Typescript 1.8.x与当时React的(明确键入的)类型描述文件结合使用时,我们使用“事件”类型在React组件属性中声明“通用”事件。然后,我们可以将该属性(being和event handler函数)的值附加到例如HtmlInputElement的“onChange”属性上

interface IIcoonProps {
    onClick?: Event;
}

interface IIcoonDetails {
    cssClass: string;
    standaardTooltip: string;
}

class Icoon extends React.Component<IIcoonProps, {}> {



public render(): JSX.Element {

    return (<span   className={klassenamen}
                    title={nieuweTooltip}
                    onClick={this.props.onClick} />);
    }
}
接口IIcoonProps{
onClick?:事件;
}
接口IIC详细信息{
cssClass:字符串;
标准工具提示:字符串;
}
类ICON扩展了React.Component{
public render():JSX.Element{
返回();
}
}
我们最近更新了TypeScript 2.2.2,还更新了我们正在使用的类型定义。现在,我们不能再使用泛型“Event”类型,因为它将导致类似“type“Event”这样的异常无法分配给type“EventHandler>”

当然,当我将自定义组件的properties接口中的属性类型更改为React.MouseeEvent时,问题就解决了。但是我不想让此组件的父组件知道底层类型(在本例中为HtmlInputElement),因为它是我自己组件的属性中提到的事件。我只需要将事件传递给父组件,因为我希望父组件能够使用事件的“PreventDefault”等方法。我在IComponentProps界面中使用不同的属性和方法来发布文本输入的更改值

下面的代码正在运行,但并不可取

interface IIcoonProps {
    onClick?: React.EventHandler<React.MouseEvent<HTMLSpanElement>>;
}

interface IIcoonDetails {
    cssClass: string;
    standaardTooltip: string;
}

class Icoon extends React.Component<IIcoonProps, {}> {

public render(): JSX.Element {

    return (<span   className={klassenamen}
                    title={nieuweTooltip}
                    onClick={this.props.onClick} />);
    }
}
接口IIcoonProps{
onClick?:React.EventHandler;
}
接口IIC详细信息{
cssClass:字符串;
标准工具提示:字符串;
}
类ICON扩展了React.Component{
public render():JSX.Element{
返回();
}
}
有人知道在使用TypeScript和React时,如何像我们以前使用“event”类型时那样使用事件的泛型类型,而不使用泛型(如MouseEvent)


更新:添加了代码示例

我觉得您的代码很好,但如果您不想具体说明目标元素的类型,则可以使用:


编辑 如果希望使用非通用接口,则可以创建自己的接口,然后使用该接口:

type MouseEvent = React.MouseEvent<HTMLElement>;

interface IIcoonProps {
    onClick?: (event: MouseEvent) => void;
}
类型MouseEvent=React.MouseEvent;
接口IIcoonProps{
onClick?:(事件:MouseEvent)=>void;
}

您能添加一个代码示例来说明问题吗?@NitzanTomer我添加了一个代码示例。我不想让父组件知道“Icoon”组件的底层Html是一个“HtmlSpanElement”。当我将来需要更改此选项时,我可能需要更改所有使用“Icon”组件的组件。这不是我所希望的答案,而是我所期望的。感谢您建议使用HtmleElement而不是专用标记。这将提高代码的可维护性。您希望得到什么?我希望得到一个不使用泛型并公开preventDefault等方法的接口。我可以将此接口作为可选参数添加到回调函数中。请检查我修改的应答器。这并没有真正改变解决方案,但看起来更简单。MouseEvent只是一个别名。我同意你最初的回答!
interface IIcoonProps {
    onClick?: (event: React.MouseEvent<HTMLElement>) => void;
}
type MouseEvent = React.MouseEvent<HTMLElement>;

interface IIcoonProps {
    onClick?: (event: MouseEvent) => void;
}