我在组件中传递道具并直接在 suneditor 中使用..
const SunEditorForRendering: React.FC<Props> = ({postContent }) => {
const [content, setContent] = useState("hello world");
const editor = useRef<SunEditorCore>();
// The sunEditor parameter will be set to the core suneditor instance when this function is called
const getSunEditorInstance = (sunEditor: SunEditorCore) => {
editor.current = sunEditor;
};
useEffect(() => {
if (postContent) {
editor.current?.core.setContents(postContent);
}
}, [postContent]);
<SunEditor
getSunEditorInstance={getSunEditorInstance}
//setContents={content}
setContents={postContent}
onChange={handleOnChange}
/>
}
上面的代码无法按预期工作,并且编辑器的内容多次过时。但是,如果我不直接使用 postcontent 并首先将其保存在一个 state 中,然后将 state 设置为 editor ,它就可以正常工作。工作代码是
const SunEditorForRendering: React.FC<Props> = ({postContent }) => {
const [content, setContent] = useState("hello world");
const editor = useRef<SunEditorCore>();
// The sunEditor parameter will be set to the core suneditor instance when this function is called
const getSunEditorInstance = (sunEditor: SunEditorCore) => {
editor.current = sunEditor;
};
useEffect(() => {
if (postContent) {
setContent(postContent);//----> first save postcontent to new state
}
}, [postContent]);
useEffect(() => {
if (content) {
editor.current?.setContents(content)//---> here set content to editor
}
},[content]);
<SunEditor
getSunEditorInstance={getSunEditorInstance}
setContents={content}
onChange={handleOnChange}
/>
}
还有其他代码,但在上述两种情况下它们都是相同的