如何在反应中从文本区域获取选定的文本? [英] How to get the selected text from text area in react?

查看:45
本文介绍了如何在反应中从文本区域获取选定的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 react 中制作一个文本编辑器.有谁知道如何从 textarea 中获取选定的文本,以便可以在选定的文本上应用样式.我知道我们可以在 javascript 中使用 window.getSelection 但我是想知道是否有其他方法可用于此功能?

I am trying to make a text editor in react.Does anyone knows how to get the selected text from the textarea so that styles can be applied on the selected text.I know we can use window.getSelection in javascript but I am curious to know If any other methods are available for this functionality?

推荐答案

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

Yes there is a method to do this, specially in React. The way you should go to achieve this is as follow.

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

step 1:- use ref in your textarea ui element. like

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

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

step 2:- now you can access the DOM element,using react refs.

    let textVal = this.refs.myTextarea; 

第 3 步:- 使用 selectionStart 和 selectionEnd :- 使用 selectionStart 和
selectionEnd 你可以了解你的开始和结束指针
选定的文本.这可以做如下;

step 3:- use selectionStart and selectionEnd :- using selectionStart and
selectionEnd you can get to know your start and end pointer
of selected text.which can be done as below;

        let cursorStart = textVal.selectionStart;
        let cursorEnd = textVal.selectionEnd;

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

now you have start and end index of your selected text.

第 4 步:- 使用 javascript 子字符串函数获取所选文本.

step 4 :- use javascript substring function to get the selected text.

    this.state.textareaVal.substring(cursorStart,cursorEnd) 

这篇关于如何在反应中从文本区域获取选定的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆