最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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)}
/>
发布评论

评论列表(0)

  1. 暂无评论