【问题标题】:React Typescript how send props and use it in child componentReact Typescript 如何发送道具并在子组件中使用它
【发布时间】:2020-08-09 10:14:22
【问题描述】:

我正在使用 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;

这是项目父组件中的错误

(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)

在常规 react 和 es6 中,我可以像这样在子组件中使用这个道具:

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

但是如果它是 TypeScript,是否在子组件中使用这个道具?

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:

    您需要指定子组件想要的道具类型。例如:

    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>
      )
    }
    

    【讨论】:

    • 和父组件无关?只需要给子组件赋值就行了?
    • 要修复您看到的错误,在父级中不需要任何内容​​。如果父母有道具,它应该得到类似的待遇。即使它没有道具,最好还是给它一个类型,只是没有任何道具:const ParentComponent: React.FC = () =&gt; {
    【解决方案2】:

    添加到回复中,如果props可以为null,则打个问号。

    interface ChildComponentProps {
      items?: Item[]
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-21
      • 2022-11-12
      • 2016-09-15
      • 2022-01-12
      • 2021-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-29
      相关资源
      最近更新 更多