在Amplify-Typescript-React应用中使用withAuthenticator需用什么类型?
在React+TypeScript中使用Amplify withAuthenticator的正确类型配置
1. 导入所需类型
从@aws-amplify/ui-react导入WithAuthenticatorProps、User以及可选的WithAuthenticatorOptions类型,覆盖组件参数和配置的类型校验需求。
2. 为App组件定义Props类型
将App组件的props类型指定为WithAuthenticatorProps,直接识别传入的user和signOut参数,消除TS7031类型警告。
3. 修复导出时的类型警告
若仍出现TS2345警告,可显式指定withAuthenticator的泛型参数,确保组件类型匹配。
完整示例代码
import { Amplify } from "aws-amplify"; import { withAuthenticator, WithAuthenticatorProps } from "@aws-amplify/ui-react"; import "@aws-amplify/ui-react/styles.css"; // 必须导入样式文件 Amplify.configure({ Auth: { region: "你的AWS区域", userPoolId: "你的用户池ID", userPoolWebClientId: "你的客户端ID", // 其他Auth配置项 }, }); // 使用WithAuthenticatorProps定义组件props function App({ user, signOut }: WithAuthenticatorProps) { return ( <div> <h1>欢迎,{user?.username}</h1> <button onClick={signOut}>退出登录</button> </div> ); } // 显式指定泛型消除导出时的类型警告 export default withAuthenticator<typeof App>(App);
额外说明
WithAuthenticatorProps已内置user(类型为User | undefined)和signOut(类型为() => Promise<void>),无需单独定义。- 若需自定义登录界面、跳转规则等,可传入第二个配置参数,并使用
WithAuthenticatorOptions约束配置对象类型。
内容的提问来源于stack exchange,提问作者reikje
相关产品推荐
相关产品推荐

