如何将 RichUtils 与 React Hooks 结合使用

How to use RichUtils with React Hooks

我正在尝试实现一个按钮,该按钮在单击后将内联样式更改为粗体。我想实现这个 example 但使用 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;

我不是很清楚为什么,但你的焦点功能似乎打断了大胆的切换。删除它允许切换功能与您链接到的示例相同。

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>
  );
};