reactjs - 在 React 中使用 typescript 传递功能性道具
问题描述
我将使用 typescript 将功能性道具从父组件传递给子组件:
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
. 现在您可以指定MouseEvent
发生在哪个元素上React.MouseEvent<HTML***Element>
现在您的点击发生在子元素中的一个按钮上,event.target
该元素标签的 contains 属性。例如<button name="bla" id="bla" onClick={***} />
,事件包含name
、id
,当然还有标记名本身。
所以一般的点击事件就像
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
推荐阅读
- json - 在树状结构中以角度显示 Jason 数据
- sql - 使用“with”子句
- vuejs2 - 如何在使用 Vuetify v.1.5 的项目中仅覆盖 Vuetifyjs v.2 中的一种样式
- excel - 循环槽细胞时获取超链接
- angular - 无法将 http 请求发布到 .Net Core 2.1 Web 项目
- graphql - Apollo 客户端本地状态 - LoggedIn 查询
- assembly - 十六进制值中的前导零
- react-native - react-native-calendars:呈现事件计数而不是markedDates中的点
- c# - 阻止用户查看未分配给其 userId 的表中的项目
- c# - 包含列表的 HttpChannel MarshalByRefObject