[使用多输入聊天信息时如何将内部状态设置为空字符串

问题描述 投票:0回答:1

我使用的是mui-rte,它是关于draftjs的很好的Material-ui包装器:

https://github.com/niuware/mui-rte.git

我想使用MUIRichTextEditor作为网络聊天客户端的输入字段。在点击发送按钮后,我遇到了如何将内部状态设置为空字符串的障碍。 RTE编辑器组件如下所示:

import React, {useState, useEffect} from "react";
import MUIRichTextEditor from "mui-rte";
import {convertToRaw, EditorState} from 'draft-js'
import {stateFromMarkdown} from "draft-js-import-markdown";
import { ThemeProvider } from '@material-ui/styles';
import { createMuiTheme, useTheme} from '@material-ui/core/styles';

const local_theme_overrides = {
    overrides: {
        MUIRichTextEditor: {
            root: {
                marginTop: 20,
                width: "80%"
            },
            editor: {
                border: "1px solid gray",
                borderRadius: 4
            }
        }
    }
};

export default function RichTextEditor(props)
{
    const { initialValue, onChange, ...rest } = props;
    const [initial, setInitial] = useState('');

    useEffect(() => {
        const init_state = EditorState.createWithContent(stateFromMarkdown(initialValue));
        setInitial(JSON.stringify(convertToRaw(init_state.getCurrentContent())));
        onChange(init_state);
    }, []);

    const theme = useTheme();
    const [localTheme, setLocalTheme] = useState(theme);

    useEffect(() => {
        setLocalTheme(Object.assign({...theme}, local_theme_overrides));
    }, []);

    return (
        <ThemeProvider theme={localTheme}>
            <MUIRichTextEditor
                onChange={onChange}
                value={initial}
                {...rest}
            >
            </MUIRichTextEditor>
        </ThemeProvider>
    );
}

父母使用这样的字段:

const [message_content, setMessageContent] = useState('');

function sendMessage() {
    if (message_content === '')
        return;
    let rte_markdown = stateToMarkdown(message_content.getCurrentContent());
    channel.sendMessage(rte_markdown);
    // I would like to reset or re-render the mui-tre component after sending the message
    //setMessageContent('');
}

.....
<RichTextEditor
    label={"Write a message to " + name}
    initialValue={''}
    onChange={data => setMessageContent(data)}
    placeholder={"Write a message to " + name}
    controls={[]}
/>

<Button
        autoFocus
        onClick={() => sendMessage()}
        disabled={message_content === ''}
>
     Send
</Button>

按下发送按钮后,消息将传递到聊天频道,但是我无法重置或强制重新渲染RTE组件。关于如何做到这一点的任何想法?

reactjs react-hooks draftjs rte
1个回答
0
投票

您可以将MUI文本编辑器的value属性设置为空内容状态。状态必须是严格的和原始的。

一种方法是从draft-js库(构建了mui-rte)中导入EditorState对象和convertToRaw方法:

import { EditorState, convertToRaw } from 'draft-js'

const emptyContentState = JSON.stringify(
    convertToRaw(EditorState.createEmpty().getCurrentContent())

<MUIRichTextEditor value={emptyContentState} />
© www.soinside.com 2019 - 2024. All rights reserved.