React函数组件用Hooks取输入值时报setName未定义该如何解决?
错误原因
你在解构useState返回值时没有添加变量声明关键字const,导致name、setName、phone、setPhone未被声明为组件内部的局部变量,被识别为全局变量:
- 浏览器全局作用域本身存在内置属性
name,因此触发no-restricted-globals校验报错 - 其余未声明的变量直接使用时触发
no-undef报错
修复代码
只需要给两行解构语句加上const声明即可:
import React , {useState} from 'react' const NewCustomer = () => { // 新增const声明局部变量 const [name , setName] = useState(''); const [phone , setPhone] = useState(''); const addCustomer= ()=>{ console.log(name , phone); } return ( <CForm action="submit" > <CFormGroup row> <CCol md="3"> <CLabel >Name </CLabel> </CCol> <CCol xs="12" md="9"> <CInput type="text" onChange={e=> setName(e.target.value)} autoComplete="" /> </CCol> </CFormGroup> <CFormGroup row> <CCol md="3"> <CLabel > Phone number</CLabel> </CCol> <CCol xs="12" md="9"> <CInput type="number" onChange={e=> setPhone(e.target.value)} autoComplete="current-tel"/> </CCol> </CFormGroup> <CButton type="submit" onClick={()=> addCustomer()} > Insert </CButton> </CForm> ) }
补充优化建议
如果需要避免表单默认提交导致的页面刷新问题,可以把提交逻辑绑定到CForm的onSubmit事件上,同时调用e.preventDefault(),比单独给按钮绑定点击事件更符合表单交互规范。
内容的提问来源于stack exchange,提问作者Gandom
相关产品推荐
相关产品推荐

