Reactjs 如何将光标移动到行尾?
我正在使用draft.js开发一个富文本编辑器。我希望用户能够在单击斜体按钮后继续键入。在用户禁用斜体按钮之前,应应用内联样式。单击按钮使光标在编辑器外聚焦。我创建了一个ref,在当前ref上调用了Reactjs 如何将光标移动到行尾?,reactjs,draftjs,Reactjs,Draftjs,我正在使用draft.js开发一个富文本编辑器。我希望用户能够在单击斜体按钮后继续键入。在用户禁用斜体按钮之前,应应用内联样式。单击按钮使光标在编辑器外聚焦。我创建了一个ref,在当前ref上调用了focus()函数,然后在edotorState上调用了moveFocusToEnd。这不符合预期。我如何实现这种行为 ReactJS import React from 'react'; import { Editor, EditorState, RichUtils } from 'draft-js
focus()
函数,然后在edotorState
上调用了moveFocusToEnd
。这不符合预期。我如何实现这种行为
ReactJS
import React from 'react';
import { Editor, EditorState, RichUtils } from 'draft-js';
import { Button, Icon } from 'antd';
function MyEditor() {
const ref = React.useRef(null);
const [editorState, setEditorState] = React.useState(
EditorState.createEmpty()
);
const handleKeyCommand = command => {
const newState = RichUtils.handleKeyCommand(editorState, command);
if (newState) {
setEditorState(newState)
return "handled"
}
return "not-handled";
}
const onItalicClick = event => {
ref.current.focus()
EditorState.moveFocusToEnd(editorState)
setEditorState(RichUtils.toggleInlineStyle(editorState, 'ITALIC'))
}
const onUnderLinkClick = event => {
event.preventDefault()
setEditorState(RichUtils.toggleInlineStyle(editorState, "UNDERLINE"))
}
const onBoldClick = event => {
event.preventDefault()
console.log(event)
setEditorState(RichUtils.toggleInlineStyle(editorState, "BOLD"))
}
return <div>
<div>
<Button
onClick={onItalicClick}
>
<Icon type="italic" />
</Button>
<Button
onClick={onUnderLinkClick}
>
<Icon type="underline" />
</Button>
<Button
onClick={onBoldClick}
>
<Icon type="bold" />
</Button>
</div>
<Editor
editorState={editorState}
onChange={editorState => setEditorState(editorState)}
handleKeyCommand={handleKeyCommand}
ref={ref}
/>
</div>;
}
export default MyEditor;
.wrapper {
border: 1px solid #e2e2e2;
padding: 10px;
margin-bottom: 20px;
}
在这里,您可以将focusOffset设置为该块的文本长度。第一条语句获取光标的位置,第二条语句将光标的偏移量设置为5,即5个字符。您必须在块中已经给出文本长度。您是否尝试使用React-Dev工具调试代码?
selectionState = this.state.editorState.getSelection()
selectionState=selectionState.merge({'forceKey':xxxx, focusOffset:5})