我正在使用TS
3.7.4,并且相信现在大多数类型都是通过接口制成的。
我有一个看起来像这样的道具:
images={
[
{
image: 'https://www.commerciallistings.cbre.co.uk//resources/fileassets/GB-Plus-480572/09e35192/11%20Strand%201_Photo_1_small.jpg',
altTag: "An Image"
},
{
image: 'https://www.commerciallistings.cbre.co.uk//resources/fileassets/GB-Plus-480572/09e35192/11%20Strand%201_Photo_1_small.jpg',
altTag: "An Image"
}
]
}
我想使用界面,因为我觉得这不太冗长。
我尝试过:
images: Array[object]
首先为图像对象创建一个接口。然后将图像prop声明为该接口的array和数组。
Interface Image {
image?: String;
altTag?: String;
}
...
images: Image[]
老实说,我不建议您屈服,但我建议您阅读文档,因为这是一项非常基本的任务,如果您无法正确掌握这些基础知识,将来您会很费劲。
首先,您需要定义您的Image对象Interface。简单地传递一个默认的Object
作为类型,几乎破坏了typescript的用途-您想要尽可能地明确,这几乎不是一个好主意。
interface ImageType {
image: string,
altTag: string,
}
然后定义您的道具
interface Props {
images: ImageType[] // Alternatively Array<ImageType>
}
const MyComponent: React.FC<Props> = (props: Props) => {
// ...
}
您可以创建如下界面:
export interface ImageProps{
image: string,
altTag: string
}
您可以像这样使用它:
const Image = ({ props: ImageProps[] }){
// Your code here.
}
希望这对您有用。