javascript - onChange doesn't work when value of input clears - Stack Overflow

I have a problem in handling input's value changingso here is my code in react,onChange works but

I have a problem in handling input's value changing so here is my code in react,onChange works but when i clear the default value it doesn't log anything until i do another change.

<Form.Control
  type="text"
  placeholder="name"
  defaultValue={this.state.name}
  onChange={e=>console.log(e.target.value)}
/>

I wrote console.log just for test.

I have a problem in handling input's value changing so here is my code in react,onChange works but when i clear the default value it doesn't log anything until i do another change.

<Form.Control
  type="text"
  placeholder="name"
  defaultValue={this.state.name}
  onChange={e=>console.log(e.target.value)}
/>

I wrote console.log just for test.

Share Improve this question edited Jul 18, 2021 at 4:41 mostafa asked Jul 18, 2021 at 4:27 mostafamostafa 711 silver badge7 bronze badges 6
  • 3 conosle.log Don't you think there is a typo here – DecPK Commented Jul 18, 2021 at 4:28
  • you wrote conosle.log instead of console.log – user14779090 Commented Jul 18, 2021 at 4:34
  • There is a typo mistake in console.log – Sanket Shah Commented Jul 18, 2021 at 4:42
  • yes i changed it but still doesn't work – mostafa Commented Jul 18, 2021 at 4:42
  • The onChange event occurs when the contents of the input are changed and focus is moved out from the input. When you clear the name the contents change but the focus is still on input and so it does not fire onChange event. I guess maybe this will answer your question. You can try using value instead of defaultValue – Sanket Shah Commented Jul 18, 2021 at 4:49
 |  Show 1 more ment

4 Answers 4

Reset to default 2

Value is not changing because in reactjs ponent rerenders once state chages and using console.log on onChange does not update any change in state. so you have to update the state on onChange event,

Try following, I am assuming it is class ponent as you have used this.state.name

<Form.Control
  type="text"
  name="name"
  placeholder="name"
  defaultValue={this.state.name || ""}
  value={this.state.name}
  onChange={e=>this.setState({name:e.target.value})}
/>

Use value instead of default value:

<Form.Control
  type="text"
  placeholder="name"
  value={this.state.name || ""}
  onChange={e=>console.log(e.target.value)}
/>

Try using an empty value instead of giving it null

<Form.Control
  type="text"
  placeholder="name"
  value={this.state.name || ""}
  onChange={e=>console.log(e.target.value)}
/>

Updated

Try with uncontrolled input:

<Form.Control
    type="text"
    placeholder="name"
    onChange={(e) => console.log(e.target.value)}
/>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745142463a4613492.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信