【问题标题】:How to use RichUtils with React Hooks如何将 RichUtils 与 React Hooks 一起使用
【发布时间】:2020-02-26 02:28:13
【问题描述】:

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

【问题讨论】:

    标签: reactjs react-hooks draftjs


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回答,德鲁。我快疯了。但是还有一个问题,即使通过在 boldText() 函数中添加 e.preventDefault() ,编辑器也会通过单击按钮失去焦点。解决方案是使用“onMouseDown”而不是使用“onClick”。然后一切都按预期工作。
    • Drew 和 Eric,非常感谢,请写博客或视频,我坚持
    猜你喜欢
    • 2021-07-09
    • 2021-12-09
    • 2020-01-06
    • 2019-10-23
    • 2022-11-29
    • 2019-08-17
    • 2020-08-02
    • 1970-01-01
    相关资源
    最近更新 更多