javascript 在React中将光标发送到输入值的末尾

nfeuvbwi  于 2024-01-05  发布在  Java
关注(0)|答案(4)|浏览(122)

当我点击删除时,我动态地向输入字段传递一个值(为了编辑最后一个输入条目)。
我可以看到,在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
非常感谢你的帮助!

ulmd4ohb

ulmd4ohb1#

另一个简单的解决方案:

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

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

6qqygrtg

6qqygrtg2#

您可以显式设置光标位置,为此将其添加到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 && hasTiles && tag === '' ) {后添加e.preventDefault()
编辑Pen

k5ifujac

k5ifujac3#

对于那些来到这里试图使用这个与React挂钩
一个简单的texfield组件,它将输入的类型切换为password/text,这是一个典型的例子,你想让用户通过点击一个按钮来切换类型并查看值来查看他们的密码。

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>
  );
}

字符串

628mspwn

628mspwn4#

一个非常简单的技巧,为我工作是-设置值的重点。
例如

const [val, setVal] = useState();
...
<input 
  val={val} 
  onFocus={
    ()=>{
      setVal(val + " "); 
      setTimeout(() => setVal(val.slice(0, val.length-1), 0);
    }
 ...
/>

字符串

相关问题