如何从文本区域中获取所选文本?

aki*_*san 5 textarea reactjs

我正在尝试在文本编辑器中做出反应.有人知道如何从textarea中获取所选文本,以便可以在所选文本上应用样式.我知道我们可以在javascript中使用window.getSelection但我很想知道如果有任何其他方法可用于此功能?

小智 8

是的,有一种方法可以做到这一点,特别是在React中.你应该如何实现这一目标如下.

第1步: - 在textarea ui元素中使用ref.喜欢

     `<textarea
           className='html-editor'  
           ref='myTextarea' 
          value = {this.state.textareaVal}
          onChange={(event)=>{
                      this.setState({
                         textareaVal:event.target.value;
                      });
                   }}
       >
      </textarea>` 
Run Code Online (Sandbox Code Playgroud)

第2步: - 现在您可以使用react refs访问DOM元素.

    let textVal = this.refs.myTextarea; 
Run Code Online (Sandbox Code Playgroud)

步骤3: - 使用selectionStart和selectionEnd: - 使用selectionStart和
selectionEnd,您可以了解
所选文本的开始和结束指针.如下所示:

        let cursorStart = textVal.selectionStart;
        let cursorEnd = textVal.selectionEnd;
Run Code Online (Sandbox Code Playgroud)

现在您有所选文本的开始和结束索引.

第4步: - 使用javascript substring函数获取所选文本.

    this.state.textareaVal.substring(cursorStart,cursorEnd) 
Run Code Online (Sandbox Code Playgroud)