Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 在React中使用typescript传递功能性道具_Reactjs_Typescript_Function_React Props - Fatal编程技术网

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

Reactjs 在React中使用typescript传递功能性道具,reactjs,typescript,function,react-props,Reactjs,Typescript,Function,React Props,我将使用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 d

我将使用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,{Component}来自“react”
从“./Child”导入子项
//某种类型声明
类父级扩展组件{
状态={
id:0;
名称:'sample'
}
//一些代码
//我不知道如何声明下面函数的类型!!!
onChildClickedHandler=(目标:HTMLInputElement)=>{
this.setState({id:target.id})
}
渲染(){
}
}
导出默认父级

从“React”导入React
接口IChild{
//我不知道如何声明下面函数的类型!!!
onChildClicked:({target:HTMLInputElement})=>void
名称:string
}
const Child:React.SFC=({onChildClicked,name})=>{
返回(
OnChildClick(目标)}>
{name}
OnChildClick(目标)}>
{name}
)
}

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

存在一些问题: 当您单击一个元素时,会发生一个
MouseEvent
,可由
React.MouseEvent
定义。现在您可以通过
React.MouseEvent
指定
MouseEvent发生在哪个元素上

现在,您的单击发生在child中的一个按钮上,
event.target
包含该元素标记的道具。例如,
事件包含
名称
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>)
handleClick(事件:React.MouseEvent)
//将'target'从'even'和'name,id'从'target'分解为
handleClick({target:{name,id}}}:React.MouseEvent)
所以你的界面应该是

onChildClicked: ({target:{name,id}}: React.MouseEvent<HTMLButtonElement>) => void
onChildClicked:({target:{name,id}}}:React.MouseEvent)=>void
有关更多事件类型(特别是鼠标事件),请查看

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