React Typescript如何发送道具并在子组件中使用它

ciz*_*z30 5 javascript typescript reactjs

我正在使用 React 和 TypeScript 并尝试将一些数据(例如 prop)传递给子组件并在子组件中使用它。但我收到错误,我不明白为什么会发生以及如何修复它。我也是 TypeScript 的初学者。

这是我的父组件

import * as React from "react";
import ChildComponent from "./ChildComponent";

const data = [
  {
    title: "A",
    id: 1,
  },
  {
    title: "B",
    id: 1,
  },
];

const ParentComponent = () => {
   return (
      <ChildComponent items={data} />
   )
}

export default ParentComponent;
Run Code Online (Sandbox Code Playgroud)

这是项目父组件中的错误

(JSX attribute) items: {
    title: string;
    id: number;
}[]
Type '{ items: { title: string; id: number; }[]; }' is not assignable to type 'IntrinsicAttributes'.
  Property 'items' does not exist on type 'IntrinsicAttributes'.ts(2322)
Run Code Online (Sandbox Code Playgroud)

当在常规的 React 和 es6 中时,我可以在子组件中使用这个 props,如下所示:

const ChildComponent = (props) => {
   return (
      <div>
         {props.items.map((item) => (
           <p to={item.title}></p>
         ))} 
      </div>
   )
}
Run Code Online (Sandbox Code Playgroud)

但是如果子组件是 TypeScript,是否可以在子组件中使用此属性?

Nic*_*wer 7

您需要指定子组件想要什么类型的 props。例如:

interface Item {
  title: string;
  id: number;
}

interface ChildComponentProps {
  items: Item[]
}

const ChildComponent: React.FC<ChildComponentProps> = (props) => {
  return (
    <div>
      {props.items.map((item) => (
        <p to={item.title}></p>
      ))} 
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

  • 和父组件无关?只需要为子组件分配类型,对吧? (2认同)