ค้นหาเว็บไซต์

reactjs - Typescript ข้อผิดพลาด: อาร์กิวเมนต์ประเภท 'NodeListOf | undefined' ไม่สามารถกำหนดให้กับพารามิเตอร์ประเภท 'Iterable' ...


ในแอป React/Typescript ของฉัน ฉันกำลังเข้าถึงอาร์เรย์ของอินพุตในอีเวนต์ลิสต์เนอร์ผ่านการใช้ 'e.currentTarget' ฉันใช้ Array.from() เพื่อแปลง NodeListOf เป็นอาร์เรย์ และได้ตรวจสอบให้แน่ใจว่าได้ตั้งค่า TS.config.json ของฉันเป็น 'es2015' อย่างไรก็ตาม ฉันได้รับข้อผิดพลาดนี้
ข้อผิดพลาด

แปลกดีที่ข้อผิดพลาดนี้ไม่ได้เกิดขึ้นในไดเรกทอรีเดิมของฉัน ฉันได้ทำการคัดลอกโฟลเดอร์โปรเจกต์ของฉัน ลบโมดูลของ node บีบอัดเป็นไฟล์ซิป และเปิดใหม่ และนั่นคือเวลาที่ข้อผิดพลาดนี้เกิดขึ้น ยังไม่แน่ใจว่าจะจัดการกับปัญหานี้อย่างไร ถ้าใครมีข้อเสนอแนะหรือวิธีแก้ไข จะขอบคุณมาก

    e: React.ChangeEvent<HTMLInputElement> | React.KeyboardEvent<Element>,
    letter: string,
    idx: number,
  ) => {
    const fields: HTMLInputElement[] = Array.from(
      e.currentTarget.parentElement?.parentElement?.querySelectorAll('input')
 )

    const length: number = fields.length
    const position: number = fields.indexOf(e.target)

คำตอบ #1

คุณไม่ได้ให้โค้ดมามาก แต่ฉันเดาว่าสิ่งนี้เกิดขึ้นเพราะ e.currentTarget.parentElement?.parentElement?.querySelectorAll('input') อาจเป็น undefined ได้ undefined ไม่สามารถใช้เป็นอาร์กิวเมนต์สำหรับ Array.from ได้ เพราะ undefined ไม่สามารถทำซ้ำได้ คุณจำเป็นต้องตรวจสอบให้แน่ใจก่อนที่จะส่งให้ Array.from มีสองวิธีแก้ปัญหาที่เป็นไปได้:

  1. ตรวจสอบว่า NodeList ที่คุณกำลังกำหนดเป้าหมายมีอยู่จริง จากนั้นจึงมอบหมายตัวแปรของคุณ
if (document.querySelector('.maybe')?.parentElement?.querySelectorAll('.doesnt-exist?')) {
  const fields = Array.from(document.querySelector('.maybe')!.parentElement!.querySelectorAll('.doesnt-exist?'))
}
  1. กำหนด NodeList ที่อาจเกิดขึ้นให้กับตัวแปร แต่ตั้งค่าเริ่มต้นเป็น [] เผื่อกรณีจำเป็น ทำการแปลงตัวแปรนั้นเป็น HTMLInputElement[] โดยอัตโนมัติ จากนั้นสามารถใช้งานใน Array.from ได้อย่างปลอดภัย:
const checker = 
  document.querySelector('.maybe')?.parentElement?.querySelectorAll('.doesnt-exist?') ?? [] as HTMLInputElement[]

const fields: Element[] = Array.from(checker)

สนามเด็กเล่น TS