我正在使用功能组件编写一个React应用程序,并决定使用TypeScript。我知道如何键入函数的参数及其返回值:
const myFunc: string = (a:number, b:number): string => a + '' + b
但是如何指定我的React组件返回其他组件的数组呢?
给定a.tsx中的组件A:
export default const A = (props) => <div>Count {props.count}</div>
和b.tsx中的组件B:
import A from './a';
const B = (list: number[]) => list.map(el => <A count={el}>)我尝试了const B = (list: number[]): A[] => list.map(el => <A count={el}>),但它给出的错误是A在这里被用作一个值,而A是一个期望的类型。有道理,但是,组件的类型是什么呢?
如何输入输出React组件集合的React功能组件?
发布于 2020-03-26 22:37:15
您不必特别说明该组件返回一个数组。通常,您使用带有类型参数的React.FC作为组件的属性:
import A from './a';
const B: React.FC<{list: number[]}> = ({list}) => list.map((el, i) => <A key={i} count={el}/>);或
import A from './a';
interface BProps {
list: number[];
}
const B: React.FC<BProps> = ({list}) => list.map((el, i) => <A key={i} count={el}/>);关于这一点的三个附注:
list是props对象的属性。在你的问题中它是它自己的形参,你需要在另一个组件中使用component.A B上的结束/,所以数组中的条目需要有一个key属性。上面的代码使用了它们在列表中的位置,但我建议您阅读有关键和使用索引作为键的this information。基本上,如果列表可以重新排序,不要使用索引作为键。:-)https://stackoverflow.com/questions/60868265
复制相似问题