我是 React、ionic、tsx 等新手,我看过很多 stackoverflow 和教程,但找不到任何可以转移到我的设置中的内容。
我正在尝试在类组件中设置一个状态以提供给子组件,以便它们可以使用 useState 挂钩访问变量,以便它们可以在另一个组件中使用 setState 后更新渲染。基本上,我试图在 IonHeader 中获取登录按钮,以使用 firebase 对用户进行身份验证。然后,该组件可以利用 onAuthStateChanged 挂钩通过 setState 更新状态。然后,IonContent 中的其他组件可以使用 useState 获取回调,并显示或不显示其内容,具体取决于用户是否登录。我可能需要将类实例绑定到 setState 函数,以便子级可以访问该函数和状态?
我试图解决的问题是同步单独的子组件可以监听和修改的状态,以提醒其他组件使用新状态进行渲染。对于 auth 和 db 对象,我可以将它们放入各自的组件中。
我将用来自 auth 的用户替换“test: String”,如果为 null,则它将是一个对象。这样我就可以检查用户是否登录。这一切都包含在 IonReactRoute 中并且
States.tsx
export interface States extends React.PropsWithChildren{
db: Firestore,
auth: Auth,
test: String,
}
按钮.tsx
export const LoginButton: React.FC<States> = (children, props) =>
{
return (
<Fragment>
<div id='divLogin'>
<button>login {props.test}</button>
{props.children}
</div>
</Fragment>
)
}
首页.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>
);
}
};
我不明白这里出了什么问题,我将返回包装为仅一个元素,并通过 PropsWithChildren 提供了子道具。如果我在 LoginButton 内添加文本,则会收到“类型 '{children: string; }' 缺少类型 'States' 中的以下属性:db、auth、test”。如果我在其中添加任何元素,错误消息会发生变化,那么如何在其中添加任何子组件呢?我认为 PropsWithChildren 会为我解决这个问题!
不知道这是否是一个好的解决方案,或者它是否有效,任何反馈都值得赞赏!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
之所以显示
“Type '{}'等,是因为state字段继承自React.Component默认情况下,this.state的类型为Readonly,当您像{...this.state}那样展开它时>,结果的类型为{}。您使用
作为States并没有改变this.state的类型。这类似于在let A: Superclass = B as Subclass中,A的类型将是 Superclass,而不是 Subclass。解决输入问题的一种方法是覆盖
state字段的类型。export default class Home extends React.Component{ state: States constructor(props: Props) { ... } ... }另一种方法是显式指定通用
React.Component的类型参数,其中P代表 props,Scode> 用于状态。