简体   繁体   English

当输入值清除时 onChange 不起作用

[英]onChange doesn't work when value of input clears

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.我在处理输入值更改时遇到问题,所以这里是我的代码反应,onChange 有效,但是当我清除默认值时,它不会记录任何内容,直到我进行另一次更改。

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

I wrote console.log just for test.我写了 console.log 只是为了测试。

Value is not changing because in reactjs component rerenders once state chages and using console.log on onChange does not update any change in state.值不会改变,因为在 reactjs 组件中,一旦状态改变就会重新渲染,并且在onChange上使用console.log不会更新任何状态变化。 so you have to update the state on onChange event,所以你必须更新 onChange 事件的状态,

Try following, I am assuming it is class component as you have used this.state.name尝试以下,我假设它是类组件,因为您已经使用了 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})}
/>

Updated更新

Try with uncontrolled input:尝试使用不受控制的输入:

<Form.Control
    type="text"
    placeholder="name"
    onChange={(e) => console.log(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尝试使用空值而不是给它 null

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM