问题描述
我正在使用 Draft.js 库,但我不完全知道如何将基于类的代码转换为基于函数的代码。
constructor(props) {
super(props);
this.state = { };
const content = window.localStorage.getItem('content');
if (content) {
this.state.editorState = EditorState.createWithContent(convertFromraw(JSON.parse(content)));
} else {
this.state.editorState = EditorState.createEmpty();
}
}
如果有人能帮忙,那将是一个很大的帮助,谢谢。
解决方法
要为您的 editorState
设置初始状态,您可以使用 useState
钩子。这个初始状态可以是一个函数,它只会在初始渲染时执行。在您想要从本地存储获取初始数据的情况下,这很有用。在此函数中返回您要设置的值 editorState
。
useState
钩子返回一个状态值 (editorState
) 和一个更新它的函数 (setEditorState
)。您可以将这些传递给您的 Draft.js Editor
组件:
function MyInput() {
const [editorState,setEditorState] = React.useState(() => {
const content = window.localStorage.getItem('content');
return content
? EditorState.createWithContent(convertFromRaw(JSON.parse(content)))
: EditorState.createEmpty();
});
return <Editor editorState={editorState} onChange={setEditorState} />;
}
,
这可能有帮助
export function Example(props){
const [editorState,setEditorState] = React.useState(); // define state here
const content = window.localStorage.getItem('content');
if (content) {
setEditorState(EditorState.createWithContent(convertFromRaw(JSON.parse(content))));
} else {
setEditorState(EditorState.createEmpty());
}
}