使用React在文本区域中更改光标位置

2021/01/31 04:51 · jquery ·  · 0评论

我在React中有一个文本区域,我想变成一个“记事本”。这意味着我希望“ 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”键,光标也始终出现在字符串的末尾。有谁知道如何正确设置光标位置?

您必须在状态更新更改光标位置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
              });
      }
 }

jsfiddle

对于正在寻找快速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为输入不再聚焦时的

这是一个挂钩风格的体系结构中的解决方案。我的建议是更改文本区域,valueselectionStart在插入制表符时立即更改

import React, { useRef } from "react"

const CodeTextArea = ({ onChange, value, error }) => {
  const textArea = useRef()
  return (
      <textarea
        ref={textArea}
        onKeyDown={e => {
          if (e.key === "Tab") {
            e.preventDefault()

            const { selectionStart, selectionEnd } = e.target

            const newValue =
              value.substring(0, selectionStart) +
              "  " +
              value.substring(selectionEnd)

            onChange(newValue)
            if (textArea.current) {
              textArea.current.value = newValue
              textArea.current.selectionStart = textArea.current.selectionEnd =
                selectionStart + 2
            }
          }
        }}
        onChange={e => onChange(e.target.value)}
        value={value}
      />
  )
}

React 15 最好的办法是类似的东西:

class CursorForm extends Component {

  constructor(props) {
    super(props);
    this.state = {value: ''};
  }

  handleChange = event => {
    // Custom set cursor on zero text position in input text field
    event.target.selectionStart = 0 
    event.target.selectionEnd = 0

    this.setState({value: event.target.value})
  }

  render () {
    return (
      <form>
        <input type="text" value={this.state.value} onChange={this.handleChange} />
      </form>
    )  
  }

}

您可以通过event.target.selectionStartevent.target.selectionEnd完全控制光标位置,无需访问实际的DOM树。

本文地址:http://jquery.askforanswer.com/shiyongreactzaiwenbenquyuzhonggenggaiguangbiaoweizhi.html
文章标签: ,   ,  
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!