【发布时间】:2021-06-20 13:09:15
【问题描述】:
我有在里面渲染一些文本的反应组件,但是我如何动态选择一段文本并将其包装在一个跨度中。
代码示例
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>
);
}
当我选择文本时,会触发一个函数,该函数接收所选文本的坐标并对其进行处理,所以这就是我将所选文本包装在跨度中并将新文本设置为 setState 的方法,这将是旧的文本包含在 span 中的文本
【问题讨论】:
标签: reactjs