如何从反应中的文本区域获取选定的文本?

How to get the selected text from text area in react?

我正在尝试在 react.Does 中制作一个文本编辑器 任何人都知道如何从文本区域中获取选定的文本,以便可以在选定的文本上应用样式 text.I 知道我们可以使用 [= javascript 中的 14=] 但我很想知道是否还有其他方法可用于此功能?

在 React 中制作文本编辑器的最佳方法是使用 DraftJS

如果您使用的是 React,那么 DraftJS 是实现它的最佳方式。它消除了您在尝试从头开始创建自己的文本编辑器时可能面临的许多挑战。这包括管理编辑器的状态(类似于管理组件状态的方式)、管理文本选择、应用不同的属性等等。

你可以 get started by checking out the docs,我建议你观看该页面上的介绍视频,其中介绍了 DraftJS 旨在解决的困难。

希望对您有所帮助。

是的,有一种方法可以做到这一点,特别是在 React 中。您应该按照以下方式实现这一目标。

第 1 步:- 在文本区域 ui 元素中使用 ref。喜欢

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

第 2 步:- 现在您可以使用 React 引用访问 DOM 元素。

    let textVal = this.refs.myTextarea; 

第 3 步:- 使用 selectionStart 和 selectionEnd :- 使用 selectionStart 和
selectionEnd 你可以知道你的开始和结束指针
选定的 text.which 可以按以下方式完成;

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

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

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

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

如何在功能组件中实现?扩展 Sanjeev 给出的答案。

function MyEditor() {

const [state,setValue] = useState({value: ""});

//1
const myRef = React.createRef()

const inputsHandler = (e) =>{
    var taxt = e.target.innerHTML
    let textArray = taxt.split(/\n/gm)
    console.log(textArray)
    setValue( {value: e.target.value} )
}

const onDone = () => {
    console.log("on done", stateNew)
    dispatch(updateEditorVisibility())
    // dispatch(props.reducer(state.value))
    dispatch(stateNew.editorReducerAction(state.value))
}



return (
    <div>
        <textarea 
         type="text"
         ref={myRef} 
         name="first_name" 
         onChange={inputsHandler} 
         value={state.value}/>
         <button onClick={() => {       
                let textVal = myRef.current;
                let cursorStart = textVal.selectionStart;
                let cursorEnd = textVal.selectionEnd;
                let selectedText = state.value.substring(cursorStart,cursorEnd) 
                console.log(selectedText)
            }}>Log</button>
    </div>
)}
  1. 使用 create ref 创建一个 ref

    const myRef = React.createRef();

  2. 在您的文本区域中设置引用 ref={myRef}

  3. 访问使用

                let cursorStart = textVal.selectionStart;
                let cursorEnd = textVal.selectionEnd;
                let selectedText = state.value.substring(cursorStart,cursorEnd) 
                console.log(selectedText)````