Sharepoint web part / react app error: Property 'show' does not exist on type 'Readonly<{}>'

Sharepoint web part / react app error: Property 'show' does not exist on type 'Readonly<{}>'

我已经有很长一段时间没有用 React 做过任何事情了,更不用说我在 sharepoint 中没有做太多了。我使用 yeoman 生成器创建了一个简单的 React 应用程序,但现在我在尝试连接状态时遇到了问题。

以下代码生成此错误:属性 'show' 在类型 'Readonly<{}>' 上不存在。

还有其他几个 post 关于导致此问题的原因,但我无法在我的应用程序中成功修复它。生成器似乎创建并引用了 props 文件。我看到一个 post 说我需要为状态创建(和引用)一个类似的文件?我试过仍然无法让它工作。任何帮助将不胜感激。

import * as React from 'react';
import styles from './SpetSelfServiceQuestionnaire.module.scss';
import { ISpetSelfServiceQuestionnaireProps } from './ISpetSelfServiceQuestionnaireProps';
import { escape } from '@microsoft/sp-lodash-subset';    

 export default class SpetSelfServiceQuestionnaire extends React.Component<ISpetSelfServiceQuestionnaireProps, {}> {

  constructor( props ) {
    super( props );
    this.state =  { show: true }
    this.toggleDiv = this.toggleDiv.bind(this)
  }

  toggleDiv = () => {
    const { show } = this.state;
    this.setState( { show: !show })
  }
React.Component<ISpetSelfServiceQuestionnaireProps, {}>

泛型的第二个参数是状态的类型。你说过状态将是一个空对象,所以当你尝试做其他事情时,打字稿会指出不匹配。

看起来你希望状态是这样的:

interface ISpetSelfServiceQuestionnaireState {
  show: boolean;
}

export default class SpetSelfServiceQuestionnaire extends React.Component<
  ISpetSelfServiceQuestionnaireProps,
  ISpetSelfServiceQuestionnaireState
> {
  //...
}

它不需要在另一个文件中,除非你想要它。