React Select onChange报错:undefined is not an object (evaluating 'a.props.inputProps.ref')
问题:react-select onChange触发"undefined is not an object (evaluating 'a.props.inputProps.ref')"错误
我在Next.js客户端组件中使用react-select实现国家选择器,代码如下:
"use client"; import { useState, useMemo } from "react"; import Header from "@/components/Header"; import PhoneInput from "@/components/PhoneInput"; import countryList from "react-select-country-list"; import Select from "react-select"; export default async function Dashboard() { const [country, setCountry] = useState(""); const options = useMemo(() => countryList().getData(), []); return ( <form className="bg-white shadow-sm ring-1 ring-gray-900/5 sm:rounded-xl md:col-span-2"> <div className="sm:col-span-4"> <label htmlFor="country" className="block text-sm font-medium leading-6 text-gray-900"> Country </label> <div className="mt-2"> <Select id="country" name="country" options={options} value={country} onChange={(selectedOption) => setCountry(selectedOption.value)} autoComplete="country-name" className="block w-full py-1.5 text-gray-900 shadow-sm focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:max-w-xs " /> </div> </div> </form> ); }
选择国家时,控制台抛出错误:undefined is not an object (evaluating 'a.props.inputProps.ref'),打印selectedOption结果为{label:"United States",value:"US"}。
原因分析
react-select组件要求value属性传入完整的选项对象(包含label和value字段),但你当前的country state是字符串类型(比如"US"),组件内部会把这个字符串当作选项对象去读取props.inputProps.ref,导致读取undefined的属性报错。
解决方法
- 调整state的初始值为
null(表示初始未选择),或者传入符合选项结构的对象(比如默认选中美国:{label: "United States", value: "US"}) - 修改
onChange逻辑,直接保存选中的完整选项对象,而不是只存value字符串 - 若表单提交时仅需提交国家编码,在提交时提取
country.value即可
修改后的完整代码:
"use client"; import { useState, useMemo } from "react"; import Header from "@/components/Header"; import PhoneInput from "@/components/PhoneInput"; import countryList from "react-select-country-list"; import Select from "react-select"; export default function Dashboard() { // 初始值改为null,或者默认选中的完整选项对象 const [country, setCountry] = useState(null); const options = useMemo(() => countryList().getData(), []); return ( <form className="bg-white shadow-sm ring-1 ring-gray-900/5 sm:rounded-xl md:col-span-2"> <div className="sm:col-span-4"> <label htmlFor="country" className="block text-sm font-medium leading-6 text-gray-900"> Country </label> <div className="mt-2"> <Select id="country" name="country" options={options} value={country} // 直接保存选中的完整对象 onChange={(selectedOption) => setCountry(selectedOption)} autoComplete="country-name" className="block w-full py-1.5 text-gray-900 shadow-sm focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:max-w-xs" /> </div> </div> </form> ); }
注:另外注意组件不要用async声明,因为客户端组件不需要异步导出,虽然这不是当前报错的直接原因,但可能引发其他问题
内容的提问来源于stack exchange,提问作者donzee529
相关产品推荐
相关产品推荐

