2017-08-11 128 views
2

我有一個打字稿組件做出反應,看起來是這樣的:如何使用TypeScript爲React組件回調指定函數參數?

interface FooDetails { 
    name: string 
    latitude: number, 
    longitude: number, 
} 

interface FooSelectorProps { 
    onDetailsChanged: Function, 
} 

class FooSelector extends React.Component<FooSelectorProps, any> { 
    constructor(props: FooSelectorProps, context) { 
     super(props, context); 
    } 

    onTravelTypeChange(event) { 
     this.setState({ travelType: event.target.value }); 
    } 

    onDetailsChange(fooData) { 
     this.props.onDetailsChanged({ 
      name: fooData.name, 
      latitude: fooData.latitude, 
      longitude: fooData.longitude, 
     }); 
    } 

    render() { 
      return <div>...Foo selection UI...</div> 
    } 
} 

我希望能夠指定在我propTypes的onDetailsChanged功能(FooSelectorProps)需要FooDetails對象,但我可以」弄清楚如何做到這一點。

+1

不確定,但檢查此鏈接,可能會有所幫助:[** LINK **](https://stackoverflow.com/questions/29689966/typescript-how-to-define-type-for-a-function -callback-as-any-function-type-no) –

+1

[Typescript:如何爲方法參數中使用的函數回調(如任何函數類型,不通用)定義類型](https:// stackoverflow的.com /問題/ 29689966 /打字稿-如何到限定型換一個函數回調-AS-任何功能型無) –

回答

2

而不是使用類型的onDetailsChanged全球型Function的,你可以寫出來的類型,而不是,所以更改FooSelectorProps到:

interface FooSelectorProps { 
    onDetailsChanged: ((details: FooDetails) => void) 
} 

,那麼你會得到類型檢查爲onDetailsChanged回調。

相關問題