我有一个管理面板,用户可以通过它编辑网站上的促销活动。我在 NEXT.js (React) 上的项目。我想做一个独立的文本编辑器,里面会有段落、字体和字体样式。我以前没有处理过这个,因为我是初学者。在这个阶段,我正在尝试获取突出显示的文本并将其设为粗体。告诉我它是如何实现的:
const [selectText, setSelectText] = useState('')
const textRef = useRef(null);
function consolText() {
let cursorStart = textRef.current.selectionStart;
let cursorEnd = textRef.current.selectionEnd;
setSelectText(textRef.current.value.substring(cursorStart,
cursorEnd))
}
选项2
const [selectText, setSelectText] = useState('')
const [selectTextAnswer, setSelectTextAnswer] = useState('')
const [cursorStart, setCursorStart] = useState('')
const [cursorEnd, setCursorEnd] = useState('')
const textRef = useRef(null);
function consolText() {
setCursorStart(textRef.current.selectionStart);
setCursorEnd(textRef.current.selectionEnd);
setSelectTextAnswer(textRef.current.value.substring(cursorStart, cursorEnd))
console.log(selectTextAnswer)
}
html
<textarea ref={textRef} value={selectText} onChange={e =>setSelectText(e.target.value)}</textarea>
<button onClick={consolText}>selectText</button>
我的错误 我得到了突出显示的值,但我必须连续按两次按钮然后需要重置它?以及如何制作所选部分,例如 fdf
或者也许有人正在使用 suneditor
谢谢
如果您必须按两次按钮,请尝试使用普通变量而不是 useState。