gpt4 book ai didi

javascript - 通过 HOC 提供数据,但调用组件时出现 Property '' is Missing in type '{}' but required in type '' 错误

转载 作者:行者123 更新时间:2023-12-02 22:38:04 24 4
gpt4 key购买 nike

我有以下 HOC 组件为我的组件提供 firebase:

import React from 'react'

const FirebaseContext = React.createContext({})

export const withFirebase = <Props extends object>(
Component: React.ComponentType<Props>
): React.ComponentType<Props> =>
class WithFirebase extends React.Component<Props> {
render(): React.ReactNode {
return (
<FirebaseContext.Consumer>
{(firebase): React.ReactNode => (
<Component {...this.props} firebase={firebase} />
)}
</FirebaseContext.Consumer>
)
}
}

export default FirebaseContext

我的组件如下所示:

import React from 'react'
import Firebase, { withFirebase } from '../Firebase'


interface FirebaseInterface {
firebase: Firebase
}

const SignInGoogle: React.FC<FirebaseInterface> = ({ firebase }) => {
//component content
}

export default withFirebase(SignInGoogle)

但是每当我在页面中调用组件时,都会收到以下错误:类型“{}”中缺少属性“firebase”,但类型“FirebaseInterface”中需要属性“firebase”SignInEmail.tsx(48, 3):“firebase”在此处声明。 (我的组件)

Firebase 是由我的 HOC 组件提供的,那么如何消除此错误?我究竟做错了什么?

最佳答案

问题是您实际上减少了 withFirebase HOC 中所需的属性,但您的返回类型并未反射(reflect)这一点。尝试:

import React from 'react'

const FirebaseContext = React.createContext({})

export const withFirebase = <Props extends { firebase: Firebase }>(
Component: React.ComponentType<Props>
): React.ComponentType<Omit<Props,'firebase'>> =>
class WithFirebase extends React.Component<Props> {
render(): React.ReactNode {
return (
<FirebaseContext.Consumer>
{(firebase): React.ReactNode => (
<Component {...this.props} firebase={firebase} />
)}
</FirebaseContext.Consumer>
)
}
}

export default FirebaseContext

Omit 帮助器需要 ts 3.5,但它也可以在 react 类型中使用(我认为)。给定一个需要 firebase 的组件,返回一个不需要的组件

关于javascript - 通过 HOC 提供数据,但调用组件时出现 Property '' is Missing in type '{}' but required in type '' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58680352/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com