Búsqueda de sitios web

reactjs - React + Typescript - Errores de tipado en refs


He visto muchas otras preguntas con el mismo problema que el mío, y he probado todas las soluciones, pero no funciona. Tengo un formulario con muchos campos, que he personalizado en FloatingLabelInputs. Tienen un método público llamado resetState, que quiero llamar. Así es como se ve mi componente con el formulario:

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' }
];

Por lo que he visto en otras preguntas, esto debería funcionar, ya que he tipeado la propiedad fieldsRefs usando React.RefObject. Sin embargo, no funciona, y el error que me da TypeScript es el siguiente:

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'.

Si intento console.log(this.fieldsRefs), todo funciona, sin embargo. Solo recibo el error y me veo obligado a hacer un cast as any.

Respuesta #1

Deberías revisar la interfaz de props del componente <FloatingLabelInput />: parece que requiere una ref de tipo RefObject<HtmlInputElement> y estás intentando darle un RefObject<FloatingLabelInput>.

Deberías intentar cambiar el tipo de React.RefObject<FloatingLabelInput> a React.RefObject<HtmlInputElement>

Respuesta #2

Prueba este tipo: React.MutableRefObject<HTMLInputElement | null>

Artículos relacionados