Ionic React.FC props PropsWithChildren error“Type '{}' is missing the following properties from type 'States':VisualStudioCode中的db,auth,test”

xytpbqjk  于 2023-05-27  发布在  Ionic
关注(0)|答案(1)|浏览(504)

我是react,ionic,tsx和所有这些的新手,我看了很多stackoverflow和教程,但找不到任何东西可以转移到我的安装程序中。
我试图在类组件中设置一个状态,以给予给子组件,以便它们可以使用useState钩子访问变量,以便它们可以在另一个组件中使用setState后更新render。基本上,我试图在IonHeader中获得一个登录按钮,以使用firebase对用户进行身份验证。然后,该组件可以使用onAuthStateChanged钩子用setState更新状态。然后,IonContent中的另一个组件可以使用useState获取回调,并根据用户是否登录显示其内容。我可能需要将类示例绑定到setState函数,以便子函数可以访问该函数和状态?
我试图解决的问题是同步一个状态,单独的子组件可以监听和修改该状态,以提醒其他组件使用新状态进行渲染。对于auth和db对象,我可以将它们放在各自的组件中。
我将替换“测试:字符串'与用户从auth,要么它将是一个对象,如果空。这样我就可以检查用户是否已登录。这一切都被包裹在IonReactRoute和
States.tsx

export interface States extends React.PropsWithChildren{
    db: Firestore,
    auth: Auth,
    test: String,
}

Button.tsx

export const LoginButton: React.FC<States> = (children, props) =>
{
  return (
    <Fragment>
    <div id='divLogin'>
      <button>login {props.test}</button>
      {props.children}
    </div>
    </Fragment>
  )
}

Home.tsx

export default class Home extends React.Component{
  constructor(props) {
    super(props)
    // init firebase app
    initializeApp(firebaseConfig)
    // init services
    this.state = {
      db: getFirestore(),
      auth: getAuth(),
      test: 'teststring'
    } as States
  }

  render() {

    return (
      <IonPage>
        {/* Header */}
        <IonHeader translucent>
          <IonToolbar>
            <IonTitle>Hydroponics-lurvas777</IonTitle>
            <LoginButton {...this.state}></LoginButton>
            {/*^^^^ this gives error: "Type '{}' is missing the following properties from type 'States': db, auth, test"*/}
          </IonToolbar>
        </IonHeader>
        <IonContent fullscreen>
          {/* Condense header for ios devices, larger to smaller header */}
          <IonHeader collapse="condense" translucent>
            <IonToolbar>
              <IonTitle size="large">Hej ios</IonTitle>
              </IonToolbar>
          </IonHeader>
          {/* Here's the real content, everything is toggles by auth state */}
        </IonContent>
      </IonPage>
    );
  }
};

我不明白这里出了什么问题,我只将返回 Package 到一个元素,并通过PropsWithChildren提供了children prop 。如果我在LoginButton中添加文本,我会得到“Type '{ children:string; }”缺少类型“States”中的以下属性:db,auth,test”。如果我在里面添加任何元素,错误消息就会改变,那么我如何在里面添加任何子组件呢?以为PropsWithChildren会为我解决这个问题!
不知道这是不是一个好的解决方案,或者它是否会工作,任何反馈都很感激!

zd287kbt

zd287kbt1#

之所以说"Type '{}'等等,是因为state字段是从React.Component继承的。默认情况下,this.state的类型为Readonly<{}>,当您像{...this.state}一样展开它时,结果的类型为{}
您对as States的使用不会更改this.state的类型。这与let A: Superclass = B as SubclassA的类型是Superclass而不是Subclass类似。
解决键入问题的一种方法是重写state字段的类型。

export default class Home extends React.Component{
  state: States
  constructor(props: Props) {
     ...
  }
  ...
}

另一种方法是显式指定泛型React.Component<P, S>的类型参数,其中P用于props,S用于state。

export default class Home extends React.Component<Props, States>{
  constructor(props: Props) {
     ...
  }
  ...
}

相关问题