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

javascript - setState from input on change - can't delete from input - Stack Overflow

programmeradmin0浏览0评论

I have an input:

 <input type="text" value={this.state.current} onChange={this.handleChange.bind(this)} />

handleChange() method:

handleChange(e) {
  let val = parseInt(e.target.value); 
  if (val) {
    this.set(val);
  }
}

and set() method (simple set number between 1 and 5 to the state):

set(val = 1) {
  if (val < 1) {
    val = 1;
  }
  if (val > 5) {
    val = 5;
  }
  this.setState({ current: val });
}

My problem is: when i want to change value in input, i can't delete number from it. I think it is auto filled from state imediatly after I delete number. Where is the problem in my code?

exmaple on jsFiddle: /

I have an input:

 <input type="text" value={this.state.current} onChange={this.handleChange.bind(this)} />

handleChange() method:

handleChange(e) {
  let val = parseInt(e.target.value); 
  if (val) {
    this.set(val);
  }
}

and set() method (simple set number between 1 and 5 to the state):

set(val = 1) {
  if (val < 1) {
    val = 1;
  }
  if (val > 5) {
    val = 5;
  }
  this.setState({ current: val });
}

My problem is: when i want to change value in input, i can't delete number from it. I think it is auto filled from state imediatly after I delete number. Where is the problem in my code?

exmaple on jsFiddle: https://jsfiddle/4sc3p2ny/

Share Improve this question asked Jul 28, 2016 at 13:00 mwlmwl 1,48814 silver badges19 bronze badges 2
  • set(val = 1) is only for init. Even if i remove it (set(val)) i still can't delete numbers from input. – mwl Commented Jul 28, 2016 at 13:06
  • If you will remove set(val) it will not allow you to change as it shows value mapped to current , which will not change if you will remove set(val) – Pardeep Dhingra Commented Jul 28, 2016 at 13:10
Add a ment  | 

2 Answers 2

Reset to default 6

When you are trying pletely remove value from input, e.target.value returns '' in this case parseInt(e.target.value) returns NaN, because parseInt('') returns NaN., you need check it and set current as empty string

 handleChange(e) {
   let val = parseInt(e.target.value);

   if (isNaN(val)) {
     this.setState({ current: '' });
   } else {
     if (val < 1) {
       val = 1;
     }

     if (val) {
       this.set(val);
     }
   }
 }

Example

Remove value={this.state.current} from the input element

发布评论

评论列表(0)

  1. 暂无评论