如何在反应打字稿中输入道具?
P粉897881626
P粉897881626 2024-03-31 15:34:36
0
2
258

如何在 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粉897881626
P粉897881626

全部回复(2)
P粉550323338

您使用 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 

您必须修复此类型以匹配从 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粉903052556

尝试将 [Props] 更改为 Props,如下所示

const Login: FC = ({ authors }) => { ... }

现在它可以工作了,因为它需要对象而不是数组,我们将传递一个像 <Loginauthors={authors} /> 这样的对象。现在,作者将是一个对象数组。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!