如何在 React TypeScript 中輸入 props ?我收到錯(cuò)誤屬性“authors”在類型“[Props] & {children?: ReactNode; 上不存在” }'.ts。我期望傳遞一個(gè)由名稱和密碼鍵組成的數(shù)組。
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 ( ... ) }
,即使我正在傳遞道具。
您使用 IUser 類型定義了 IUser 接口并定義了名稱、密碼狀態(tài),這將導(dǎo)致問(wèn)題,因?yàn)楫?dāng)您定義此時(shí):
const [name, setName] = useState(""); // name will expected to be name = { name: 'name', password: 'password' }
這是錯(cuò)誤的,因?yàn)槊Q,密碼是一個(gè)字符串,所以嘗試這樣定義它:
const [name, setName] = useState(""); const [password, setPassword] = useState ("");
然后您必須修復(fù)將作者傳遞給 FC 組件的問(wèn)題:
const Login: FC// instead of
您必須修復(fù)此類型以匹配從 App.tsx 傳遞的數(shù)據(jù)類型的最后一件事:
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 );
并且您像這樣從應(yīng)用程序傳遞了它:
const Authors = [ { id: "001", author_name: "John Smith", // not a name password: "123" } ];
嘗試將 [Props]
更改為 Props
,如下所示
const Login: FC= ({ authors }) => { ... }
現(xiàn)在它可以工作了,因?yàn)樗枰獙?duì)象而不是數(shù)組,我們將傳遞一個(gè)像 <Loginauthors={authors} />
這樣的對(duì)象。現(xiàn)在,作者將是一個(gè)對(duì)象數(shù)組。