我正在使用draft.js开发Rich Text编辑器。我希望用户能够在单击斜体按钮后继续输入文字。并且应该应用内联样式,直到用户禁用斜体按钮为止。单击按钮可使光标移出编辑器。我创建了一个引用,并在当前引用上调用了focus()
函数,然后在moveFocusToEnd
上调用了edotorState
。这不能按预期方式工作。如何实现这种行为?
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;
SCSS
.wrapper {
border: 1px solid #e2e2e2;
padding: 10px;
margin-bottom: 20px;
}
答案 0 :(得分:0)
selectionState = this.state.editorState.getSelection()
selectionState=selectionState.merge({'forceKey':xxxx, focusOffset:5})
在这里,您可以将focusOffset设置为该块的文本长度。