0

У меня есть компонент который рендерит текст внутри. При выделении текста я получаю его координаты, и в функции transformTextCallback вырезаю выделенный участок текста, так вот как мне обернуть этот участок в span и вернуть назад исходный текст, весь текст в котором данный участок будет обернуть в span, установить это значение в стейт и отрисовать уже новый текст с span для выделения его другим цветом

Пример кода

import { useState } from "react";
import "./styles.css";


export default function App() {

const [text, setText] = useState('Some text will be here but this one will be yellow')


const transformTextCallback = (text,start, end) => {
  let selectedString = text.substring(start, end)
  //how wrapp selectedText into span and return all text where
  //selected text will be wrapped with span
  //exprected result => Some text will <span className='red'>be here but</span> this one will be yellow
}

const onMouseUp = ()=> {
  let data = window.getSelection().getRangeAt(0)
  let start = data.startOffset; //index start select text
  let end = data.endOffset //index end select text

  let transformText = transformTextCallback(text, start, end)
  console.log(transformText)
}


  return (
    <div className="App">
      <div className='textContent' onMouseUp={onMouseUp}>
      {text}
      </div> 
    </div>
  );
}

1 ответ 1

0

function App() {
  const [text, setText] = React.useState('Some text will be here but this one will be yellow'),
        [start, setStart] = React.useState(0),
        [end, setEnd] = React.useState(0)

  const onMouseUp = ()=> {
    let data = window.getSelection().getRangeAt(0)
    setStart(data.startOffset)
    setEnd(data.endOffset)
  }

  return (
    <div className='App'>
      <div className='textContent'>
          {text.slice(0, start)}
          <span className="selected">{text.slice(start, end)}</span>
          {text.slice(end)}
      </div> 
      
      <div className='textContent' onMouseUp={onMouseUp}>
          {text}
      </div> 
    </div>
  )
}

ReactDOM.render(<App/>, document.getElementById('root'));
.selected{
  background: #f00;
}

.App{
  position: relative;
}

.textContent{
  position: absolute;
  top: 0;
  left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id='root'></div>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.