React可复用输入组件报错:Cannot read properties of undefined (reading 'length')
问题分析与修复方案
1. 核心错误原因:访问undefined的length属性
当组件未传入value属性(比如使用非受控模式,或父组件某次渲染未传递value),otherProps.value会是undefined,此时执行otherProps.value.length会抛出TypeError: Cannot read properties of undefined (reading 'length'),这是代码突然报错的最可能诱因。
2. 修复后的代码
const FormInput = ({ label, id, ...otherProps }) => { // 安全判断输入值是否存在,兼容空字符串、undefined、null及数字"0"的场景 const shouldShrink = otherProps.value != null && (otherProps.value.length > 0 || otherProps.value === "0"); return ( <div className='group'> {/* 添加id与label关联,提升可访问性 */} <input className='form-input' id={id || label?.toLowerCase().replace(/\s+/g, '-')} {...otherProps} /> {label && ( <label htmlFor={id || label?.toLowerCase().replace(/\s+/g, '-')} className={`${shouldShrink ? 'shrink' : ''} form-input-label`} > {label} </label> )} </div> ); }; export default FormInput;
3. 关键优化说明
- 空值安全处理:通过
otherProps.value != null先判断值是否存在,再处理长度逻辑,彻底避免undefined报错。 - 可访问性修复:添加
id和htmlFor关联输入框与标签,解决点击标签无法聚焦输入框的问题,符合前端可访问性标准。 - 场景兼容:单独处理输入值为
"0"的情况,避免数字输入框的合法值被误判为空。
4. 悬停效果补充实现
如果需要鼠标悬停时标签移出输入框的效果,可在label的类名中添加hover触发的动态类(需确保你的CSS框架如Tailwind支持group hover语法):
className={`${shouldShrink ? 'shrink' : ''} form-input-label group-hover:shrink`}
内容的提问来源于stack exchange,提问作者King Louis
相关产品推荐
相关产品推荐

