insert at cursor in react

↘锁芯ラ 提交于 2019-12-05 08:55:01

You need to get the node, by doing this.getDOMNode(). Depending on the rest of your code, you might need to find the textarea within that node; or refactor your textarea into its own component and use refs.

insertAtCursor: function (myField, myValue) {
    var myField = this.getDOMNode();

    // the rest of your code
}

A nicer alternative is to just determine the cursor position, and insert your new string; and store it back in your state. This is what I'd recommend.

var index = getCursorPosition();
this.setState({
  value: this.state.value.slice(0, index) + theNewString + this.state.value.slice(index + 1)
})

In React 15.6.1 best option is something like that:

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

}

You can get full control of cursor position by event.target.selectionStart and event.target.selectionEnd values without any access to real DOM tree.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!