如何使用 TypeScript 为 React 组件回调指定函数参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45629148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to specify function parameters for React component callback with TypeScript?
提问by Wilka
I have a React component in TypeScript that looks something like this:
我在 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>
}
}
I'd like to be able to specify that the onDetailsChanged
function in my propTypes (FooSelectorProps
) takes a FooDetails
object, but I can't figure out how to do that.
我希望能够指定onDetailsChanged
propTypes ( FooSelectorProps
)中的函数接受一个 FooDetails
对象,但我不知道如何做到这一点。
回答by Wilka
Instead of using the global type Function
for type of onDetailsChanged
, you can write out the type instead, so change FooSelectorProps
to:
您可以将类型写出,而不是使用全局类型Function
作为 type of onDetailsChanged
,因此更改FooSelectorProps
为:
interface FooSelectorProps {
onDetailsChanged: ((details: FooDetails) => void)
}
then you'll get type checking for the onDetailsChanged
callback.
然后你会得到onDetailsChanged
回调的类型检查。