如何解决如何将其转换为基于函数的 React 代码?
我正在使用 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());
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。