首页 > 解决方案 > 如何在反应打字稿中呈现本地存储中的数据?

问题描述

当我单击保存时,我希望数据显示在我的保存按钮下方的浏览器中,我该怎么做?我正在使用对打字稿模板做出反应。

 function ButtonDefaultExample(props: IButtonExampleProps) {
  const { disabled, checked } = props;
  const [showEditor, setShowEditor] = useState(false);
  const [showLesson, setShowLesson] = useState(false);

  return (
    <div style={{width: '80%', margin:'0px auto'}}>
      <h1>Click to create a new course.</h1>
      <Stack horizontal tokens={{childrenGap:10}} horizontalAlign="center" style={{width:'100%'}}>
        <DefaultButton text="Create Course" onClick={()=>setShowLesson(true)} allowDisabledFocus disabled={disabled} checked={checked} />
      </Stack>
      <br><br>
      {
        showLesson && (
          <DefaultButton text="Create Lesson" onClick={()=>setShowEditor(true)} allowDisabledFocus disabled={disabled} checked={checked} style={{alignItems:'center'}} />
        )
      }
      {
        showEditor && (
          <SunEditor onChange={ (content: string) => {
            localStorage.setItem("Contents", content);
          } } />
        )
      }
      <DefaultButton text="Save" onClick={() => localStorage.getItem("Contents") } allowDisabledFocus disabled={disabled} checked={checked} />
    </div>
  );
}

标签: javascriptreactjstypescriptreact-tsxreact-typescript

解决方案


也许你可以把它保存在一个状态中,然后显示它。

尝试这个

function ButtonDefaultExample(props: IButtonExampleProps){
  const { disabled, checked } = props;
  const [showEditor, setShowEditor] = useState(false);
  const [showLesson, setShowLesson] = useState(false);
  const [showContent, setShowContent] = useState('');

   

  return (
    <div style={{width: '80%', margin:'0px auto'}}>
      <h1>Click to create a new course.</h1>

      <Stack horizontal tokens={{childrenGap:10}} horizontalAlign="center" style={{width:'100%'}}>
        <DefaultButton text="Create Course" onClick={()=>setShowLesson(true)} allowDisabledFocus disabled={disabled} checked={checked} />
      </Stack>
      <br></br>
      {
        showLesson && (
          <DefaultButton text="Create Lesson" onClick={()=>setShowEditor(true)} allowDisabledFocus disabled={disabled} checked={checked} style={{alignItems:'center'}} />
        )
      }
      {
        showEditor && (
          <SunEditor onChange={ (content: string) => {
            localStorage.setItem("Contents", content);
          } } />
        )

      }
     <DefaultButton text="Save" onClick={() => setShowContent(localStorage.getItem("Contents")) } allowDisabledFocus disabled={disabled} checked={checked} />
     {showContent}
    </div>
  );
 }

推荐阅读