如何使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:48:35  来源:igfitidea点击:

How to specify function parameters for React component callback with TypeScript?

reactjstypescript

提问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 onDetailsChangedfunction in my propTypes (FooSelectorProps) takes a FooDetailsobject, but I can't figure out how to do that.

我希望能够指定onDetailsChangedpropTypes ( FooSelectorProps)中的函数接受一个 FooDetails对象,但我不知道如何做到这一点。

回答by Wilka

Instead of using the global type Functionfor type of onDetailsChanged, you can write out the type instead, so change FooSelectorPropsto:

您可以将类型写出,而不是使用全局类型Function作为 type of onDetailsChanged,因此更改FooSelectorProps为:

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

then you'll get type checking for the onDetailsChangedcallback.

然后你会得到onDetailsChanged回调的类型检查。