2017-08-11 41 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回调。

相关问题