Eri*_*dán 5 reactjs draftjs react-hooks
我正在尝试实现一个按钮,单击它后将内联样式更改为粗体。我想使用 React Hooks 来实现这个例子。
单击按钮后,RichUtils 正在执行,但不会将文本更改为粗体。我缺少什么?
import React, { useEffect, useRef, useState } from 'react';
import {Editor, EditorState, RichUtils} from 'draft-js';
const MyEditor = () => {
const [editorState, setEditorState] = useState(EditorState.createEmpty());
const editor = useRef(null);
const focusEditor = () => {
editor.current.focus();
}
const boldText = () => {
let nextState = RichUtils.toggleInlineStyle(editorState, 'BOLD');
setEditorState(nextState);
}
return (
<div onClick = {focusEditor}>
<button onClick = { () => boldText()}>Bold</button>
<Editor
ref = {editor}
editorState = {editorState}
onChange = {editorState => setEditorState(editorState)}
/>
</div>
);
}
export default MyEditor;
Run Code Online (Sandbox Code Playgroud)
我不太清楚为什么,但你的焦点功能似乎中断了大胆的切换。删除它可以使切换功能与您链接到的示例相同。
const MyEditorFunctional = () => {
const [editorState, setEditorState] = useState(EditorState.createEmpty());
const boldText = () => {
const nextState = RichUtils.toggleInlineStyle(editorState, "BOLD");
setEditorState(nextState);
};
return (
<div>
<button type="button" onClick={boldText}>
Bold
</button>
<Editor
editorState={editorState}
onChange={setEditorState}
/>
</div>
);
};
Run Code Online (Sandbox Code Playgroud)