insert at cursor in react

前端 未结 2 674
日久生厌
日久生厌 2021-01-13 03:26

I need to insert text at caret (current cursor position) in the React-controlled textarea (like autocomplete).

For vanilla textarea I used this code:



        
2条回答
  •  北海茫月
    2021-01-13 04:24

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

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

提交回复
热议问题