反应打字稿 | 事件处理程序道具的正确类型

Jon*_*a33 2 javascript typescript ecmascript-6 reactjs

我的 App 组件将事件处理程序作为道具传递给 Button Component

// App.js

  public handlePlay = () => {
    this.setState({ ****** })
  }
Run Code Online (Sandbox Code Playgroud)
// render

<Button play={this.handlePlay} />
Run Code Online (Sandbox Code Playgroud)

通过 prop ie 传递的事件处理程序的正确类型是什么play

// Button.js
interface ButtontProps {
  play: any //what is the correct type here?
}

export const Button: React.SFC<ButtontProps> = ({ play }) => (
  <button onClick={play}>Play</button>
)

Run Code Online (Sandbox Code Playgroud)

我不想使用,any因为这会使我无法为这样的实例应用正确的类型。

Obl*_*sys 12

最简单的解决方案是使用MouseEventHandler类型 withHTMLButtonElement作为类型参数:

interface ButtonProps {
  play: React.MouseEventHandler<HTMLButtonElement>
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*vic 5

它很可能是以下之一

(event: React.MouseEvent<HTMLElement>) => void
(event: React.MouseEvent<HTMLInputElement>) => void
Run Code Online (Sandbox Code Playgroud)

您可以通过查看此处的 React 类型来确认这一点

  • @Jonca33 按照 Oblosys 的回答进行操作。用我们的任一解决方案替换您首先注释的“any”就足够了。 (2认同)