使用react-phone-number-input触发Cannot read 'target' of undefined报错如何解决
报错原因
- 你使用的
PhoneInput第三方组件的onChange回调未遵循原生input事件的传参规则,它不会传递原生事件对象作为第一个入参,而是直接返回格式化后的手机号码字符串 - 你的事件处理函数将入参误判为事件对象,尝试访问
e.target.value,但此时e本身就是手机号值,不存在target属性,因此触发Cannot read properties of undefined (reading 'target')类型错误。
修正方案
- 调整事件处理函数,直接使用入参作为手机号码值,无需访问
target属性
// class组件写法示例,若存在this指向问题可改用箭头函数定义 onSelectChange(phoneValue){ // 直接使用入参即可,不需要访问.target.value console.log(phoneValue); // 若需要更新state直接赋值 this.setState({ phone: phoneValue }) }
- 组件调用时可简化绑定逻辑(原匿名函数包裹的写法也可正常运行,只是冗余)
<PhoneInput placeholder="Enter phone number" value={this.state.phone} onChange={this.onSelectChange} />
内容的提问来源于stack exchange,提问作者streak
相关产品推荐
相关产品推荐

