gpt4 book ai didi

reactjs - 如何在 React Hooks 中使用 RichUtils

转载 作者:行者123 更新时间:2023-12-03 23:08:45 24 4
gpt4 key购买 nike

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

Edit sharp-brattain-cx97c

关于reactjs - 如何在 React Hooks 中使用 RichUtils,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60405921/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com