Dis*_*ous 17 javascript jquery reactjs
我在React有一个textarea,我想变成一个"记事本".这意味着我希望"tab"键缩进而不是无焦点.我看了这个答案,但我不能让它与React一起工作.这是我的代码:
handleKeyDown(event) {
    if (event.keyCode === 9) { // tab was pressed
        event.preventDefault();
        var val = this.state.scriptString,
            start = event.target.selectionStart,
            end = event.target.selectionEnd;
        this.setState({"scriptString": val.substring(0, start) + '\t' + val.substring(end)});
        // This line doesn't work. The caret position is always at the end of the line
        this.refs.input.selectionStart = this.refs.input.selectionEnd = start + 1;
    }
}
onScriptChange(event) {
   this.setState({scriptString: event.target.value});
}
render() {
    return (
        <textarea rows="30" cols="100" 
                  ref="input"
                  onKeyDown={this.handleKeyDown.bind(this)}
                  onChange={this.onScriptChange.bind(this)} 
                  value={this.state.scriptString}/>
    )
}
当我运行此代码时,即使我按下字符串中间的"tab"键,我的光标也总是出现在字符串的末尾.谁知道如何正确设置光标位置?
QoP*_*QoP 26
更新状态后必须更改光标位置(setState()不立即变异this.state)
为了做到这一点,你必须包装this.refs.input.selectionStart = this.refs.input.selectionEnd = start + 1;一个函数并将它作为第二个参数传递给setState(回调).
handleKeyDown(event) {
      if (event.keyCode === 9) { // tab was pressed
          event.preventDefault();
          var val = this.state.scriptString,
          start = event.target.selectionStart,
          end = event.target.selectionEnd;
          this.setState(
              {
                  "scriptString": val.substring(0, start) + '\t' + val.substring(end)
              },
              () => {
                  this.refs.input.selectionStart = this.refs.input.selectionEnd = start + 1
              });
      }
 }
对于任何正在寻找快速 React Hooks (16.8+) 光标位置示例的人:
import React, { useRef } from 'react';
export default () => {
  const textareaRef = useRef(); 
  const cursorPosition = 0;
  return <textarea
    ref = {textareaRef}
    onBlur = {() => textareaRef.current.setSelectionRange(cursorPosition, cursorPosition)}
  />
}
在本例中,setSelectionRange用于将光标位置设置cursorPosition为输入不再聚焦时的值。
更多关于 的信息useRef,可以参考 React 官方文档的Hook Part。
| 归档时间: | 
 | 
| 查看次数: | 20998 次 | 
| 最近记录: |