如何将 RichUtils 与 React Hooks 结合使用

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)

Dre*_*ese 4

我不太清楚为什么,但你的焦点功能似乎中断了大胆的切换。删除它可以使切换功能与您链接到的示例相同。

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)

编辑 Sharp-brattain-cx97c

  • 谢谢你的回答,德鲁。我快要疯了。但还有一个问题,编辑器会通过单击按钮而失去焦点,即使是在 boldText() 函数中添加 e.preventDefault() 也是如此。解决方案是使用“onMouseDown”而不是“onClick”。然后一切都会按预期进行。 (4认同)