如何在 React TypeScript 中输入道具? [关闭]

问题描述 投票:0回答:4

如何在 React TypeScript 中输入道具?我收到错误 Property 'authors' does not exist on type '[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 (
  ...
  )
}

,即使我正在传递道具。

javascript reactjs arrays typescript react-props
4个回答
0
投票

尝试将

[Props]
更改为
Props
,如下所示

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

现在它可以工作了,因为它需要对象而不是数组,我们将传递一个像

<Login authors={authors} />
这样的对象。现在 authors 将是一个对象数组。


0
投票

您可以使用

type
interface
来描述道具。 通常
interface
用来形容
objects
interfaces
以字母
I
types
T
开头也是一个很好的约定。

interface IAuthor {
  name: string;
  password: string;
}

const Login = ({ authors }: { authors: IAuthor[] ): JSX.Element => {
  return (
    ...
  )
}

在上面的示例中,

Login
组件需要一个 prop
authors
,它是由
objects
描述的
IAuthor
的数组,例如

authors = [
  {
    name: "Spiderman"
    password: "maryjane"
  },
  { 
    name: "Superman"
    password: "loislane"
  }
]

希望这有帮助。


0
投票
        type Props = {
          authors: {
            name: string;
            password: string;
          }[];
        };
        
        const Login: FC<Props> = ({ authors }) => {
          const history = useHistory();
          const [name, setName] = useState<IUser["name"]>("");
          const [password, setPassword] = useState<IUser["password"]>("");
    
    
    please use these syntaxes to fix the error. There are three errors in your code that I found.

FC<Props>
<IUser["name"]>
<IUser["password"]>

0
投票

您定义了 IUser 接口并定义了名称,密码状态为 IUser 类型,这将导致问题,因为当您定义它时:

const [name, setName] = useState<IUser>("");
// name will expected to be 
name = {
    name: 'name',
    password: 'password'
}

这是错误的,因为名称、密码是一个字符串,所以尝试这样定义它:

const [name, setName] = useState<IUser["name"]>("");
const [password, setPassword] = useState<IUser["password"]>("");

然后您必须将传递的作者修复到您的 FC 组件:

const Login: FC<Props> // 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"
   }
 ];
© www.soinside.com 2019 - 2024. All rights reserved.