Paste in cursor in real

I need to insert the text in the carriage (current cursor position) into the React- controlled text box (for example, autocomplete).

For vanilla textarea, I used this code:

insertAtCursor: function (myField, myValue) {
    // IE
    if (document.selection) {
        myField.focus();
        var sel = document.selection.createRange();
        sel.text = myValue;
    } 
    // FF
    else if (myField.selectionStart || myField.selectionStart == '0') {
        var startPos = myField.selectionStart;  var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos)
        + myValue + myField.value.substring(endPos, myField.value.length);
    } else {
        myField.value += myValue;
    }
}

but it does not work in React. How can i do this?

+4
source share
2 answers

You need to get node by doing this.getDOMNode(). Depending on the rest of the code, you may need to find the text field inside the node; or reorganize your text box into your own component and use links.

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

    // the rest of your code
}

; . , .

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

React 15.6.1 - - :

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.selectionStart event.target.selectionEnd - DOM.

+1

Source: https://habr.com/ru/post/1531816/


All Articles