首页 > 解决方案 > React:如何解决:“IntrinsicAttributes & Props”类型上不存在属性“children”

问题描述

我正在尝试从 API 获取数据并将数据显示到 React with typeScript 中的卡片列表中。由于我是 Typescript 中的 React 新手,不知道如何解决这个错误或者我错过了什么。

这是我得到的错误: Type '{ children: string[]; 键:数字;}' 不可分配给类型 'IntrinsicAttributes & Props'。类型“IntrinsicAttributes & Props”上不存在属性“children”。

这是代码:

    interface Props {
  pokemonItem: PokemonItem;
}

export const PokemonCardList = (props: Props) => {
  const { pokemonItem } = props;
  const {
    id = '',
    name = '',
    weight = '',
    height = '',
    abilities = '',
  } = pokemonItem;

  const [pokemon, setPokemon] = React.useState<PokemonItem[]>([]);
  const [loadItems, setLoadItems] = React.useState(API_URL);

  const getPokemons = async () => {
    setLoading(true);
    const response: any = await fetch(loadItems);
    const data = await response.json();

    setLoadItems(data.next);
    setPokemon(data.results[0].name);
    setLoading(false);
    
    const getEachPokemon = (result: any) => {
      result.forEach(async (element: any) => {
        const response = await fetch(
          `https:pokeapi.co/api/v2/pokemon/${element.id}`
        );
        const data = await response.json();
        // // setPokemon((currentArrayList) => [...currentArrayList, data]);
        pokemon.push(data);
      });
    };

    getEachPokemon(data.results);
    await console.log(pokemon);
  };

  React.useEffect(() => {
    return getPokemons();
  }, []);

  return (
    <div>
      {pokemon &&
        pokemon.map((item, index) => (
          <PokemonCard key={index}>
            {item.name} {item.height} {item.weight} {item.abilities}
          </PokemonCard>
        ))}
    </div>
  );
};

小精灵卡组件:

interface Props {
  pokemonItem: PokemonItem;
}

const PokemonCard = (props: Props) => {
  const { pokemonItem } = props;
  const {
    id = '',
    name = '',
    weight = '',
    height = '',
    abilities = '',
  } = pokemonItem;

  const [imageLoaded, setImageLoaded] = React.useState(false);
  const urlImage = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${id}.png?raw=true`;

  return (
    <div imageLoaded={imageLoaded}>
      <div
        src={urlImage}
        onLoad={() => setImageLoaded(true)}
      />
      <div>
        Name: {name}
        Height: {height}
        Weight: {weight}
        Abilities: {abilities}
      </div>
    </div>
  );
};

标签: reactjstypescript

解决方案


根据您对PokemonCard组件的定义,您应该传递pokemonItem如下内容:

<PokemonCard pokemonItem={item} key={item.id} />

我已经替换了key道具,因为不建议将索引用作键(请参阅文档),您可以使用项目的 id 代替。并且您需要更新PokemonCard组件的 prop 接口,以便额外的keyprop 不会破坏验证:

interface Props {
  pokemonItem: PokemonItem;
  key: string;
}

推荐阅读