在 React 中使用 typescript 传递功能性道具

Passing functional props with typescript in React

我将使用打字稿将功能道具从父组件传递到子组件:

import react, {Component} from 'react'
import Child from './Child'
//some type declaration
class Parent extends Component<{IProps},{IState}> {
state = {
id: 0;
name:'sample'
}
//some code
//I do not know how to declare type of below function!!!
onChildClickedHandler = (target:HTMLInputElement)=> {
this.setState({id:target.id})
}
render () {
<div>
<Child onChildClicked = {this.onChildClickedHandler} name={this.state.name} />
</div>
}
}

export default Parent

import React from 'react'
interface IChild  {
//I do not know how to declare type of below function!!!
onChildClicked: ({target:HTMLInputElement}) => void
name:string
}
const Child : React.SFC<IChild> = ({onChildClicked, name}) => {
return (<div>
<button type="text" id="1" onClick={({target})=>onChildClicked(target)}>
{name}
</button>
<button type="text" id="2" onClick={({target})=>onChildClicked(target)}>
    {name}
    </button>
</div>)

}

我使用解构来获取 target 而不是 event.target 来传递给函数。 如何以正确的方式在子无状态组件中声明 onChildClicked 函数的类型?

存在一些问题: 当您单击一个元素时,会发生 MouseEvent,这可以由 React.MouseEvent 定义。现在您可以通过 React.MouseEvent<HTML***Element>

指定 MouseEvent 发生在哪个元素上

现在您的点击发生在子按钮上,event.target 包含该元素标签的道具。例如 <button name="bla" id="bla" onClick={***} /> 事件包含 nameid,当然还有标记名本身。

所以一般的点击事件就像

handleClick(event: React.MouseEvent<HTMLButtonElement>)

// Destructuring `target` from `even` and `name, id` from `target` will look like 

handleClick({target:{name,id}}: React.MouseEvent<HTMLButtonElement>)

所以你的界面应该看起来像

onChildClicked: ({target:{name,id}}: React.MouseEvent<HTMLButtonElement>) => void

有关更多事件类型(特别是鼠标事件),请查看 type declaration of React by DefinitelyTyped