反应控制的输入光标跳转 [英] React controlled input cursor jumps

查看:74
本文介绍了反应控制的输入光标跳转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React并格式化了一个受控的输入字段,当我输入一些数字并在输入字段之外单击时,该输入字段可以正常工作。但是,当我要编辑输入时,光标跳到输入字段中值的前面。这仅发生在IE中,而不发生在铬。我已经看到对于某些程序员,光标会跳到该值的后面。因此,我认为我的光标跳到最前面的原因是因为该值在输入字段中向右对齐而不是向左对齐。这是一个方法:

I am using React and have formatted a controlled input field, which works fine when I write some numbers and click outside the input field. However, when I want to edit the input, the cursor jumps to the front of the value in the input field. This only occur in IE, and not in e.g. Chrome. I've seen that for some programmers the cursor jumps to the back of the value. So I think the reason that my cursor is jumping to the front is because the value is aligned to the right instead of to the left in the input field. Here is a senario:

我的第一个输入是1000
然后我想将其编辑为10003,但结果是
31000

My first input is 1000 Then I want to edit it to 10003, but the result is 31000

有没有一种方法可以控制光标不跳?

Is there a way to controll that the cursor should not jump?

推荐答案

通过您的问题来猜测,您的代码很可能看起来像这样:

Taking a guess by your question, your code most likely looks similar to this:


    <input
        autoFocus="autofocus"
        type="text"
        value={this.state.value}
        onChange={(e) => this.setState({value: e.target.value})}
    />

如果您的事件是通过 onBlur 处理的,则行为可能会有所不同同样的问题。实际上,这是预期的行为,许多人都将其称为React错误。

This may vary in behaviour if your event is handled with onBlur but essentially its the same issue. The behaviour here, which many have stated as a React "bug", is actually expected behaviour.

您的输入控件的值在加载时不是控件的初始值,而是绑定到 this.state 的基础。当状态更改时,控件由React重新呈现。

Your input control's value is not an initial value of the control when its loaded, but rather an underlying value bound to this.state. And when the state changes the control is re-rendered by React.

本质上,这意味着控件由React重新创建并由状态值填充。问题在于,它无法在重新创建之前知道光标的位置。

Essentially this means that the control is recreated by React and populated by the state's value. The problem is that it has no way of knowing what the cursor position was before it was recreated.

解决这个问题的一种方法是记住光标的位置在重新渲染之前,如下所示:

One way of solving this which I found to work is remembering the cursor position before it was re-rendered as follows:


    <input
        autoFocus="autofocus"
        type="text"
        value={this.state.value}
        onChange={(e) => {
            this.cursor = e.target.selectionStart;
            this.setState({value: e.target.value});
        }}
        onFocus={(e) => {
            e.target.selectionStart = this.cursor;
        }}
    />

这篇关于反应控制的输入光标跳转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆