使用 React hooks 处理输入时遇到问题

我尝试用钩子处理用户的文本输入。


 const [inputValues, setInputValues] = useState({

firstName:"",

lastName:"",

email:"",

telNum:"",

contactType:"Tel.",

message:"",

agree:false

});


我尝试通过以下方式更新值


  const handleChange = event => {

setInputValues({ ...inputValues, [event.target.name]: event.target.value,});

}

和事件:


onChange={handleChange}   

输入字段代码示例:


    <FormGroup row>

          <Label htmlFor='firstname' md={2}>

            First Name

          </Label>

          <Col md={10}>

            <Input

              type='text'

              id='firstname'

              name='firstname'

              placeholder='First Name'

              value={firstName}

              valid={errors.firstName === ""}

              invalid={errors.firstName !== ""}

              onBlur={handleBlur("firstName")}

              onChange={handleChange}             />

            <FormFeedback>{errors.firstName}</FormFeedback>

          </Col>

        </FormGroup>

但每当我在输入字段中输入内容时。我找不到在输入字段中输入的值。我不明白这里发生了什么。请帮助我摆脱困境


一只名叫tom的猫
浏览 132回答 2
2回答

函数式编程

您的代码中有一个拼写错误。name 属性是firstName 而不是firstname。<FormGroup row>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Label htmlFor='firstname' md={2}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; First Name&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </Label>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Col md={10}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Input&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type='text'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; id='firstname'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name='firstName'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; placeholder='First Name'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value={inputValues.firstName}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; valid={errors.firstName === ""}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; invalid={errors.firstName !== ""}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onBlur={handleBlur("firstName")}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onChange={handleChange}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <FormFeedback>{errors.firstName}</FormFeedback>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </Col>&nbsp; &nbsp; &nbsp; &nbsp; </FormGroup>

HUX布斯

替换value为value={inputValues. firstName}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript