Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何将其转换为函数基代码?_Reactjs_Draftjs - Fatal编程技术网

Reactjs 如何将其转换为函数基代码?

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

我正在使用Draft.js库,但我不完全知道如何将基于类的代码转换为基于函数的代码

构造函数(道具){
超级(道具);
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并初始化状态一次。