簡體   English   中英

在React中使用打字稿傳遞功能性道具

[英]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傳遞給函數。 如何以正確的方式在Child無狀態組件中聲明onChildClicked函數的類型?

這里有一些問題:單擊Element時,會發生一個MouseEvent ,可以通過React.MouseEvent定義React.MouseEvent 現在您可以通過React.MouseEvent<HTML***Element>指定MouseEvent發生在哪個元素上

既然您單擊了孩子中的按鈕,則event.target包含該Element標簽的道具。 例如<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

對於更多事件類型(特別是鼠標事件),請檢查React類型聲明,DefinitelyTyped

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM