使用 Typescript 进行 React 和 Google 自动完成

问题描述 投票:0回答:1

我有一个谷歌地址自动完成和一个react-bootstrap表单,但我无法使类型与

ref
匹配。

class ProfileForm extends React.Component<PropsFromRedux, ProfileFormState> {
    private myRef = React.createRef<FormControl<any>>();
    private autocomplete?: google.maps.places.Autocomplete;
    ...

}

我的Form控件是这样的:

<Form.Control ref={this.myRef} type="text" placeholder="Enter address"
              defaultValue={this.props.userProfile.location!.formatted_address}
/>

这是我创建自动完成功能的方法:

function forceCast<T>(input: any): T {
    // @ts-ignore <-- forces TS compiler to compile this as-is
    return input;
}


//@ts-ignore
    this.autocomplete = new google.maps.places.Autocomplete(
        forceCast<HTMLInputElement>(this.myRef.current),
        options);

我的问题是:

如何在不施力的情况下做到这一点?

谷歌自动完成需要一个

HTMLInputElement
(我已经尝试过很多其他类型和东西),但我能用react-bootstrap得到的最好的就是
FormControl
(我不知道如何将其“投射”到除所示内容之外的任何其他方式)。

reactjs typescript google-api react-bootstrap
1个回答
0
投票

为了避免使用

@ts-ignore
forceCast
,您可以使用
as
关键字来断言 ref 元素的类型。就您而言,您想断言
this.myRef.current
HTMLInputElement
。方法如下:

class ProfileForm extends React.Component<PropsFromRedux, ProfileFormState> {
    private myRef = React.createRef<HTMLInputElement>();
    private autocomplete?: google.maps.places.Autocomplete;
    ...

}

在你的渲染方法中:

<Form.Control ref={this.myRef} type="text" placeholder="Enter address"
              defaultValue={this.props.userProfile.location!.formatted_address}
/>

创建自动完成时,您可以直接使用

this.myRef.current
,无需任何强制转换:

this.autocomplete = new google.maps.places.Autocomplete(
    this.myRef.current!,
    options
);

通过将引用类型指定为

HTMLInputElement
,您可以告诉 TypeScript
this.myRef.current
将始终是
HTMLInputElement
,这样就无需进行强制转换或使用
@ts-ignore

© www.soinside.com 2019 - 2024. All rights reserved.