【问题标题】:Focus next input once reaching maxlength value in react without jQuery and accept only numeric values在没有 jQuery 的情况下,在达到最大长度值时关注下一个输入,并且只接受数值
【发布时间】:2017-02-10 12:52:24
【问题描述】:

我对 react 中的输入有两个问题。 有没有什么方法可以让输入在达到 maxLength 后自动聚焦下一个字段,反应 不使用 jquery

<form>
    <input type="text" maxLength="4" />
    <input type="text" maxLength="4" />
    <input type="text" maxLength="4" />
</form>

第二个问题是当 type="text" 时如何让输入只接受数值?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    为此使用 onChange 事件处理程序。当用户键入 MAX_LENGTH(4 个字符)时,焦点设置到下一个元素。 React.findDOMNode 获取与 React 组件对应的下一个 DOM 节点。 DOM 节点上的 focus 方法设置焦点。

    handleTextChange(e) {
      if (e.target.value.length <= MAX_LENGTH) {
        this.setState({ value: e.target.value });
      }
      if (e.target.value.length === MAX_LENGTH) {
        React.findDOMNode(this.nextComponent).focus();
      }
    }
    

    组件 JSX 是:

    <input value={this.state.value} onChange={this.handleTextChange} />
    <input ref={c => this.nextComponent=c} />
    

    nextComponent 在 ref 中设置。 this.nextComponent被React.findDOMNode用来获取下一个组件对应的DOM节点。

    【讨论】:

    • 我不确定您要在这里做什么。你能解释一下吗?
    • @Dan,用解释更新了答案。
    • 对于未来的读者:React.findDOMNode 已弃用,但无论如何您都不需要使用它。只需使用this.nextComponent.focus();
    【解决方案2】:

    我在上面的代码中遇到了一些错误。所以我像下面这样改变了它,它运行良好。

    handleTextChange1(e) {
        if (e.length <= 1) {
          this.setState({value: e})
        }
        if (e.length === 1) {
          this.input2.focus();
        }
      }
    

    在 TextInputComponent 我也有:

    <TextInput
        ref= {(input) => this.input1 = input}
        selectTextOnFocus={true}
        onChangeText={this.handleTextChange1}/>
    
    <TextInput
        ref= {(input) => this.input2 = input}
        selectTextOnFocus={true}
        onChangeText={this.handleTextChange2}/>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-13
      • 1970-01-01
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      • 2016-11-25
      相关资源
      最近更新 更多