【问题标题】:Send cursor to the end of input value in React在 React 中将光标发送到输入值的末尾
【发布时间】:2017-07-08 06:36:22
【问题描述】:

我在单击删除时动态地将一个值传递给我的输入字段(以编辑最后一个输入条目)。

我可以看到,在 Chrome 中,一旦输入值被渲染,光标就会显示在单词的开头,而在 Safari 和 Firefox 中,光标会出现在值的末尾,但最后一个字母会被删除。

我怎样才能始终看到光标在末尾而不删除最后一个字母(除非我按两次退格键)?

  tagEvent(e) {
    const tag = this.text.value;
    const tagGroup = tag.split(" ");
    const tiles = this.props.tiles;
    const hasTiles = Object.keys(tiles).length > 0;

    if(e.keyCode === 32 || e.keyCode === 13){
      e.preventDefault();
      tagGroup.map(tag => this.props.addTile(tag));
      this.tagForm.reset();
    }

    if(e.keyCode === 8 && hasTiles && tag === '' ) {
      this.props.editLastTile();
      this.tagForm.reset();
    }
  }

  render() {
    return (
      <div className="input-wrapper">
        <form ref={(input) => this.tagForm = input}>
          <input ref={(input) => this.text = input}
                 type="text"
                 name="new-item"
                 placeholder="type and press space"
                 autoComplete="off"
                 defaultValue={this.props.value}
                 onKeyDown={(e) => this.tagEvent(e)} />
        </form>
      </div>
    )
  }

Here a Pen with the full code

非常感谢您的帮助!

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您可以显式设置光标位置,为此将其添加到Input

    componentDidUpdate(prevProps) {
        if (prevProps.value !== this.props.value) {
            this.text.selectionStart = this.text.value.length;
            this.text.selectionEnd = this.text.value.length;
        }
    }
    

    为防止删除最后一个字符,请在 if(e.keyCode === 8 &amp;&amp; hasTiles &amp;&amp; tag === '' ) { 之后添加 e.preventDefault()

    已编辑Pen

    【讨论】:

      【解决方案2】:

      另一个简单的解决方案:

      <input ref={ref => ref && ref.focus()}
          onFocus={(e)=>e.currentTarget.setSelectionRange(e.currentTarget.value.length, e.currentTarget.value.length)}
          />
      

      ref 触发焦点,并触发onFocus 计算结束并相应地设置光标。

      【讨论】:

      • 这对我来说效果很好,因为我需要在道具中将此功能传递给孙子输入
      【解决方案3】:

      对于那些来这里尝试将其与 react hooks 一起使用的人?

      一个简单的 texfield 组件,将输入的类型切换为密码/文本,这是您希望允许用户通过单击按钮来切换类型并查看值来查看其密码的典型情况。

      function TextField() {
        const [type, setType] = useState('text');
        const inputRef = useRef(null);
        const onToggle = useCallback(() => {
          setType(current => type === 'text' ? 'password' : 'text');
          // Setting focus here
          inputRef.current.focus();
        }, []);
        useEffect(() => {
          // Moving cursor to the end
          inputRef.current.selectionStart = inputRef.current.value.length;
          inputRef.current.selectionEnd = inputRef.current.value.length;
        }, [type]);
      
        return (
          <div>
            <input
              ref={inputRef}
              type={type}
             />
             <button onClick={onToggle}>toggle type</button>
          </div>
        );
      }
      

      【讨论】:

      • 感谢您的回答。按照 MDN 的文档,这也可以通过设置 selectionStartselectionEnd 的方法 setSelectionRange 来完成,如: 。 inputRef.current.setSelectionRange(selectionStart, selectionEnd)
      猜你喜欢
      • 1970-01-01
      • 2013-07-20
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 2020-07-29
      • 1970-01-01
      • 2019-08-24
      • 1970-01-01
      相关资源
      最近更新 更多