Reactjs 如何将其转换为函数基代码?
我正在使用Draft.js库,但我不完全知道如何将基于类的代码转换为基于函数的代码Reactjs 如何将其转换为函数基代码?,reactjs,draftjs,Reactjs,Draftjs,我正在使用Draft.js库,但我不完全知道如何将基于类的代码转换为基于函数的代码 构造函数(道具){ 超级(道具); this.state={}; const content=window.localStorage.getItem('content'); 如果(内容){ this.state.editorState=editorState.createWithContent(convertFromRaw(JSON.parse(content)); }否则{ this.state.editorS
构造函数(道具){
超级(道具);
this.state={};
const content=window.localStorage.getItem('content');
如果(内容){
this.state.editorState=editorState.createWithContent(convertFromRaw(JSON.parse(content));
}否则{
this.state.editorState=editorState.createEmpty();
}
}
如果有人能帮忙,那将是一个很大的帮助,谢谢。这可能会有所帮助
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());
}
}
要设置
编辑器状态的初始状态,可以使用useState
挂钩。此初始状态可以是一个函数,它将仅在初始渲染时执行。它在您希望从本地存储获取初始数据的情况下非常有用。在此函数中,返回要设置的值editorState
useState
钩子返回一个状态值(editorState
),以及一个更新它的函数(setEditorState
)。您可以将它们传递到Draft.js编辑器
组件:
函数MyInput(){
常量[editorState,setEditorState]=React.useState(()=>{
const content=window.localStorage.getItem('content');
返回内容
?EditorState.createWithContent(convertFromRaw(JSON.parse(content)))
:EditorState.createEmpty();
});
回来
}
作为参数,您可以将函数传递给useState并初始化状态一次。