简体   繁体   English

输入表单-更改onChange和isDisabled的运行顺序

[英]Input form - change the running order of onChange and isDisabled

I have implemented in React a webpage with 3 input fields, each one with the properties of 我在React中实现了一个包含3个输入字段的网页,每个输入字段的属性为

onChange={this.handleChange} and disabled={this.isDisabled()} onChange = {this.handleChange}和Disabled = {this.isDisabled()}

The desired behavior is that when an input field contains 2 digits, the focus will be moved to the next input field. 理想的行为是,当输入字段包含2位数字时,焦点将移至下一个输入字段。 As long as the field doesn't contain 2 digits, the fields next to must be disabled . 只要该字段不包含2位数字,则必须禁用旁边的字段。

What actually happens, when I type the second digit in the first field, it runs the handleChange function, that function checks whether the field contains 2 digits, find out that yes, and moves the focus to the next input field. 实际发生的是,当我在第一个字段中输入第二个数字时,它将运行handleChange函数,该函数将检查该字段是否包含2个数字,找出是,然后将焦点移至下一个输入字段。

But the next field is disabled! 但是下一个字段被禁用! (because the isDisabled function didn't run yet!) So the cursor doesn't move.. I want to change the order of the happenings, or any other way to solve it. (因为isDisabled函数尚未运行!)因此,光标不会移动。.我想更改事件发生的顺序,或通过其他任何方法来解决。

Do you have any suggestions? 你有什么建议吗?

The problem is that this.isDisabled() runs immediately in render but this.handleChange runs on click and most possibly doesn't change the state thus no rerender. 问题是this.isDisabled()立即在render运行,但是this.handleChange在单击时运行,并且很可能不会更改状态,因此不会重新渲染。

You sholdn't run function on next input, you should pass true or false to its disabled prop. 您不要在下一个输入上运行函数,应该将truefalse传递给disabled prop。 Just make handleChange update the state which defines which fields are disabled. 只需使handleChange更新定义了哪些字段被禁用的状态即可。 And pass that state to your inputs accordingly. 然后将该状态传递给您的输入。

I had faced the same issue a few days back. 几天前我也遇到过同样的问题。 My approach was however using react states and focusing the input by its id, that was fetched from state; 但是,我的方法是使用反应状态,并通过从状态获取的id集中输入。

So first we make a input - id map for our convenience. 因此,为了方便起见,我们首先进行input - id映射。 And use document.getElementById(this.state.active).focus() function. 并使用document.getElementById(this.state.active).focus()函数。 We change our state via our change handler. 我们通过更改处理程序更改状态。

render() {
  this.setInputFocus();
  return (
     <div className="App">
       <input id="1" onChange={this.onChange} />
       <input id="2" onChange={this.onChange} />
       <input id="3" onChange={this.onChange} />
     </div>
   );
 }

 setInputFocus = () => {
   if (document.getElementById(this.state.active)) {
     document.getElementById(this.state.active).focus();
   }
 };
 onChange = e => {
   if (e.target.value.length === 2) {
     this.setState({ active: this.state.active + 1 });
   }
 };

Here is a full code that somewhat solves the issue 这是一个完整的代码,可以部分解决问题

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

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