我正在做关于 React 的 PluralSight 介绍课程,课程中的一个项目涉及构建一个允许用户输入 GitHub 用户名的 Web UI,应用程序会将相应的 GitHub 个人资料照片添加到列表中应用上的个人资料。
课程使用标准 js 编写所有内容,但我尝试使用 TypeScript,因为它是我公司使用的。我遇到了一个问题,我想将 setState(钩子)函数引用作为道具传递给子组件。
这是父组件中的代码:
function App() {
const classes = useStyles();
const [profiles, setProfiles] = React.useState<GitHubData[]>([]); // **** HOOK HERE
return (
<div>
<Typography variant="h3" className={classes.title}>The Github Cards App</Typography>
<Divider />
<Form onSubmit={setProfiles} /> // **** ISSUE IS HERE ****
<CardList profiles={profiles} />
</div>
);
}
我使用了一堆 Material-UI 的东西,但重要的是 <Form onSubmit={setProfiles} />
,它是给我错误的函数引用(在标题中指定)。
有关更多上下文,以下是相关接口和组件定义:
interface GitHubData {
name: string,
avatar_url: string,
company: string,
location?: string
}
interface updaterFunction {
updateProfiles: Dispatch<SetStateAction<GitHubData>> // From suggestions online
updateProfiles: (newProfile: GitHubData) => void // (What I hoped would work)
}
const Form = (props: updaterFunction) => { ... }
完整错误如下:
Type '{ onSubmit: Dispatch<SetStateAction<GitHubData[]>>; }' is not assignable to type 'IntrinsicAttributes & updaterFunction'.
Property 'onSubmit' does not exist on type 'IntrinsicAttributes & updaterFunction'
我该怎么做才能摆脱它?我在网上看到了一堆类似的错误,但没有一个建议的解决方案对我有用。感谢帮助!!
答案 0 :(得分:0)
看起来问题在于您的界面应该使用 onSubmit
键而不是 updateProfiles
:
interface updaterFunction {
onSubmit: ... // try with the options you mentioned
}
这就是您的错误消息中第二行似乎表明的内容。
顺便说一下,在这里将您的界面重命名为 FormProps
之类的名称是有意义的。