จะใช้ useRef กับ typescript / Formik ได้อย่างไร?

Sep 02 2020

ฉันกำลังส่งrefคุณสมบัติไปยัง FieldInput ที่กำหนดเองซึ่งฉันใช้สำหรับการตรวจสอบความถูกต้องของ Formik สำหรับแบบฟอร์มของฉัน อย่างไรก็ตามมีข้อผิดพลาด typescript บางประการ ตัวอย่างเช่นในฟังก์ชันของฉัน:

    const handleSubmitForm = (
    values: FormValues,
    helpers: FormikHelpers<FormValues>,
  ) => {

    setShowFlatList(true);
    Keyboard.dismiss();
    helpers.resetForm();
    if (fieldRef && fieldRef.current){
          fieldRef.current.blur();}
    helpers.resetForm();
  };

ฉันได้รับข้อผิดพลาดใน fieldRef.current Object is possibly 'undefined'.ว่า ฉันคิดว่าการเพิ่มเงื่อนไข if จะแก้ไขได้ แต่ไม่ได้ นอกจากนี้เมื่อฉันส่งแบบฟอร์มฉันได้รับคำเตือนว่า

Warning: An unhandled error was caught from submitForm()
Error: "fieldRef.current.blur is not a function. (In 'fieldRef.current.blur()', 'fieldRef.current.blur' is undefined)" in handleSubmitForm 

ในทำนองเดียวกันในคอมโพเนนต์ FieldInput ที่กำหนดเองของฉันที่ฉันใช้ ref={fieldRef}ฉันได้รับข้อผิดพลาดว่า:

Type '{ ref: MutableRefObject<undefined>; setFieldTouched: (field: string, isTouched?: boolean | undefined, shouldValidate?: boolean | undefined) => void; handleChange: { ...; }; ... 4 more ...; placeholderText: string; }' is not assignable to type 'IntrinsicAttributes & FieldInputProps & { children?: ReactNode; }'.
  Property 'ref' does not exist on type 'IntrinsicAttributes & FieldInputProps & { children?: ReactNode; }'.ts(2322)

ฉันจะแก้ไขสิ่งเหล่านี้ได้อย่างไร

นี่คือรหัสแซนด์บ็อกซ์:

https://snack.expo.io/@nhammad/jealous-beef-jerky-fix

คำตอบ

1 zhuber Sep 07 2020 at 11:01

หากคุณมองเข้าไปในประเภททั่วไปในปัจจุบันของคุณวิธีพารามิเตอร์แรกคือforwardRef unknownเพียงแค่เปลี่ยนวิธีการป้อนลายเซ็นของคุณเป็น

export const FieldInput = React.forwardRef<Input, FieldInputProps>(...)

typescript จะแก้ไขประเภทที่ถูกต้องโดยอัตโนมัติตามประเภทforwardRefการส่งคืนวิธี