【问题标题】:Type not assignable on Component组件上的类型不可分配
【发布时间】:2020-08-23 01:35:27
【问题描述】:

我正在学习React,所以我围绕Github API 制作了一个小应用程序,我试图列出所有用户存储库,所以我创建了一个包含以下结构的RepoItem 组件:

import React from 'react';

export interface RepoItem {
  id: string;
  name: string;
  html_url: string;
}

export const RepoItem = ({ repo }: RepoItem) => {
  return (
    <div className="card">
      <h3>
        <a href={repo.html_url}>{repo.name}</a>
      </h3>
    </div>
  );
};

然后,我有 Repos 组件调用 RepoItem 为:

import React from 'react';
import { RepoItem } from './repoItem';

interface Repos {
  repos: Array<RepoItem>;
}

export const Repos = ({ repos }: Repos) => {
  return repos.map((repo: RepoItem) => <RepoItem repo={repo} key={repo.id} />);
};

问题出在这条线上&lt;RepoItem repo={repo}

我明白了:

类型 '{ repo: RepoItem;键:字符串; }' 不可分配给类型 'IntrinsicAttributes & RepoItem'。 类型“IntrinsicAttributes & RepoItem”上不存在属性“repo”。

做错了什么?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    你应该替换

    export const RepoItem = ({ repo }: RepoItem) => {
    

    export const RepoItem = ({ repo } : { repo: RepoItem }) => {
    

    export const RepoItem: React.FC<{ repo: RepoItem }> = ({ repo }) => {
    

    否则,您输入的是props 对象,而不是props.repo

    【讨论】:

    • 如果我应用你的解决方案,我会得到:Binding element 'RepoItem' implicitly has an 'any' type.你确定吗?
    • @sfarzoso 对此感到抱歉。我添加了正确的选项。
    【解决方案2】:

    理想情况下,您只需为您的组件创建一个Props,然后添加React.SFC&lt;Props&gt; 作为最正确的返回值:

    import React from 'react';
    
    export interface RepoItem {
      id: string;
      name: string;
      html_url: string;
    }
    
    interface Props {
      repo: RepoItem
    }
    
    export const RepoItem: React.SFC<Props> = ({ repo }) => {
      return (
        <div className="card">
          <h3>
            <a href={repo.html_url}>{repo.name}</a>
          </h3>
        </div>
      );
    };
    
    

    其他组件也是如此,但请记住,SFC 用于无状态,FC 用于有状态

    【讨论】:

    • 似乎 SFC 已被弃用
    • 是的,它似乎被替换为更好的含义StatelessComponent,但这根本不是什么大问题
    猜你喜欢
    • 1970-01-01
    • 2018-07-01
    • 2020-01-02
    • 2017-09-21
    • 2019-06-10
    • 2018-10-26
    • 2020-07-08
    • 2020-04-02
    • 2020-03-17
    相关资源
    最近更新 更多