【问题标题】:What 'type' is the event for a change handler in TypeScript?TypeScript 中更改处理程序的事件是什么“类型”?
【发布时间】:2021-01-08 07:37:13
【问题描述】:

我是 TypeScript 的新手,刚刚创建了一个更改处理函数来接收事件作为设置值的参数,即event.target.value。我目前已将其设置为 any,但认为必须有正确的类型?

这是我在功能性反应组件中的方法:

const handleChange = (event: any) => {
  setValue(event.target.value);
};

【问题讨论】:

  • 这取决于您是在听原始事件还是事件处理程序。如果您使用的是 reactjs(看起来),则事件可能是 React.ChangeEvent 类型。您还可以 console.log(event) 并在其属性中查找类型。
  • 你在使用 React 吗? stackoverflow.com/questions/42081549/…
  • 是的,使用反应
  • 当我控制台日志显示它是一个 SyntheticEvent - 虽然这不是一个有效的类型..

标签: reactjs typescript


【解决方案1】:

基本 DOM 事件

基本 DOM 事件在名为 lib.dom.d.ts 的文件中定义。搜索“interface Event”,您会找到the definition in the DOM specification 的类型。

摘录如下:

/** An event which takes place in the DOM. */
interface Event {

/**
 * Returns the object to which event is dispatched (its target).
 */
readonly target: EventTarget | null;

// many, many more properties
}

如您所见,此接口将满足您的代码。但请注意,'target' 可以为 null,因此请在您的 handleChange 函数中尊重这一点:

const handleChange = (event: Event) => {

  const target = event.target; // Event | null

  if (target === null) {
     throw new Error('target can not be null');
  }

  // targets type is now Event

  setValue(target.value); // target.value is of type EventTarget
};

反应事件

其他人认为您正在使用 react。在这种情况下,请查看typings here。 您会发现一个名为“SyntheticEvent”的东西,它是“围绕浏览器原生事件的跨浏览器包装器”。

摘录:

interface BaseSyntheticEvent<E = object, C = any, T = any> {
    nativeEvent: E;
    currentTarget: C;
    target: T;
    
    // many more properties
}

interface SyntheticEvent<T = Element, E = Event> extends BaseSyntheticEvent<E, EventTarget & T, EventTarget> {}

这也满足您的代码。

阅读更多关于React Events here的信息。

【讨论】:

  • 结构良好的答案。我添加了接口并使用 BaseSyntheticEvent 代替了代码示例中的 any。发挥了魅力。
【解决方案2】:

如果您使用ChangeEvent 并提供您正在收听的元素类型,您可以避免检查以确保target 或currentTarget 是null 的额外逻辑。

例子:

const handleChange = ({
    currentTarget,
  }: ChangeEvent<HTMLInputElement>) => {
    const { name, value } = currentTarget;

【讨论】:

    猜你喜欢
    • 2020-01-02
    • 1970-01-01
    • 2021-06-02
    • 2021-07-12
    • 2016-06-28
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    相关资源
    最近更新 更多