gpt4 book ai didi

javascript - React Typescript如何发送 Prop 并在子组件中使用它

转载 作者:行者123 更新时间:2023-12-02 20:57:44 25 4
gpt4 key购买 nike

我正在使用 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 中时,我可以在子组件中使用这个 Prop ,如下所示:

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

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

最佳答案

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

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

关于javascript - React Typescript如何发送 Prop 并在子组件中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61432089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com