如何在 React TypeScript 中输入 props ?我收到错误属性“authors”在类型“[Props] & {children?: ReactNode; 上不存在” }'.ts。我期望传递一个由名称和密码键组成的数组。
https://codesandbox.io/s/test-login-page-tasks-24-04-forked-eg91s5?file=/src/components/Login.tsx:229-274
type Props = {
authors: {
name: string;
password: string;
}[];
};
const Login: FC<[Props]> = ({ authors }) => {
return (
...
)
}
,即使我正在传递道具。
P粉5503233382024-04-01 15:15:04
您使用 IUser 类型定义了 IUser 接口并定义了名称、密码状态,这将导致问题,因为当您定义此时:
const [name, setName] = useState(""); // name will expected to be name = { name: 'name', password: 'password' }
这是错误的,因为名称,密码是一个字符串,所以尝试这样定义它:
const [name, setName] = useState(""); const [password, setPassword] = useState ("");
然后您必须修复将作者传递给 FC 组件的问题:
const Login: FC// instead of <[Props]>
您必须修复此类型以匹配从 App.tsx 传递的数据类型的最后一件事:
type Props = {
authors: {
author_name: string; // instead of name
password: string;
}[];
};
// because you are passing and comparing here with author_name not with name
const userData = authors.find(
(user) => user.author_name === name && user.password === password
);
并且您像这样从应用程序传递了它:
const Authors = [
{
id: "001",
author_name: "John Smith", // not a name
password: "123"
}
];
P粉9030525562024-04-01 12:59:05
尝试将 [Props] 更改为 Props,如下所示
const Login: FC= ({ authors }) => { ... }
现在它可以工作了,因为它需要对象而不是数组,我们将传递一个像 <Loginauthors={authors} /> 这样的对象。现在,作者将是一个对象数组。