SetContents SunEditor无法在React上运行

问题描述

我一直在与SunEditor进行测试,因为我想预加载存储在数据库中的HTML文本,并允许用户在必要时对其进行修改。我从父级传递了一个ref变量,因此,当单击“提交”按钮时,他可以获得值并保存修改。 setContents有时只是工作。当我保存项目并再次编译时,出现文本。但是,如果我使用该应用程序或刷新窗口,则文本消失。我检查了变量是否仍然具有该值。我是React的新手,我不确定是做错了还是suneditor反应失败。你能帮我吗?

这是我的代码

export const TranslationArea = React.forwardRef((props,ref) =>{    
    
    const handleEditorChange = (value) => {
        console.log(value);  
    
        ref.current= value;
      }
     const handleClick  = () => {
         console.log(ref.current);
     } 
    return(
        <div>
            <h2>{props.title}</h2>
                <SunEditor 
                    autoFocus={true}
                    width="100%"
                    height="150px"
                    setoptions={{
                        buttonList: [
                            // default
                            ['undo','redo'],['bold','underline','italic','list'],['table','link','image'],['fullScreen']
                        ]
                    
                    }}
                    setContents={props.content}
                    onChange={handleEditorChange}
            
                />
                <div>{props.content}</div>
            <button onClick={handleClick}>Content</button>
        </div>
    );
});

以下是屏幕快照,其中内容正确加载到SunEditor div中(仅在编译项目时):

enter image description here

如果我刷新页面或导航到相同的链接...

enter image description here

我已经显示一个具有相同props.content的div,只是为了检查fowardRef是否正常工作。为什么setContents现在可以工作?我已经使用React工具进行检查并加载了属性

enter image description here

有什么主意吗?

解决方法

我要从父级传递一个ref变量,因此,当单击“提交”按钮时,他可以获取值并保存修改。

如果您需要访问的只是值,那么让我们传递一个回调。我们将其称为onSumbit,它将是一个从string组件中获取SunEditor值的函数。

为了访问当前已编辑的值,我在TranslationArea组件中使用了本地状态,并通过编辑器的onChange方法更新了该状态。然后,当单击“提交”按钮时,我从本地状态调用值为onSubmit的{​​{1}}。 (也许有另一种方法可以做到这一点,但我对SunEditor并不熟悉。)

content组件如下所示:

TranslationArea

我在CodeSandbox中对其进行了测试,方法是为它提供一个export const TranslationArea = ({initialContent = "",title,onSubmit}) => { const [content,setContent] = useState(initialContent); return( <div> <h2>{title}</h2> <SunEditor autoFocus={true} width="100%" height="150px" setOptions={{ buttonList: [ // default ['undo','redo'],['bold','underline','italic','list'],['table','link','image'],['fullScreen'] ] }} setContents={initialContent} onChange={setContent} /> <div>{content}</div> <button onClick={() => onSubmit(content)}>Submit</button> </div> ); }; 函数,该函数可以记录提交的内容,但是您可以使用它进行任何操作。

onSubmit

CodeSandbox Link