React + Typescript - 引用输入错误

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

我已经看到了许多其他问题与我的问题相同,我已经尝试了所有解决方案,但它无法正常工作。我有一个有许多输入的表单,我在FloatingLabelInputs中定制。他们有一个名为resetState的公共方法,我想打电话给他们。这是我的表单组件的样子:

class EditModalPage extends React.Component<Props, State> {
  fieldsRefs: React.RefObject<FloatingLabelInput>[] = fields.map(() => React.createRef());

  render() {
    return fields.map((fieldData, index) => (
      <FloatingLabelInput
        name={fieldData.name}
        ref={this.fieldRefs[index]}
      />
    ));
  }
}

const fields = [
  { name: 'test' }
];

从我在其他问题中看到的情况来看,这应该有效,因为我使用fieldsRefs键入了React.RefObject属性。但它没有,TypeScript给出的错误如下:

Type 'RefObject<FloatingLabelInput>' is not assignable to type 'string | (string & ((instance: HTMLInputElement | null) => void)) | (string & RefObject<HTMLInputElement>) | (RefObject<FloatingLabelInput> & string) | (RefObject<FloatingLabelInput> & ((instance: HTMLInputElement | null) => void)) | ... 5 more ... | undefined'.
  Type 'RefObject<FloatingLabelInput>' is not assignable to type '((instance: FloatingLabelInput | null) => void) & RefObject<HTMLInputElement>'.
    Type 'RefObject<FloatingLabelInput>' is not assignable to type '(instance: FloatingLabelInput | null) => void'.
      Type 'RefObject<FloatingLabelInput>' provides no match for the signature '(instance: FloatingLabelInput | null): void'.

如果我尝试console.log(this.fieldsRefs),一切都在运作。我只是得到错误,并被迫施放as any

reactjs typescript ref
1个回答
0
投票

你应该检查<FloatingLabelInput />组件的道具界面:它似乎需要RefObject<HtmlInputElement>类型的参考,你试图给它一个RefObject<FloatingLabelInput>

您应该尝试将类型从React.RefObject<FloatingLabelInput>更改为React.RefObject<HtmlInputElement>

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