[英]How to pass an image as prop in react/typescript to another component
我是 typescript 的新手,不知道如何在 typescript 中传递不同组件中的图像 (svg) 作为道具
这是我的代码:
图像导入
import internet from "./assets/internet.svg"
将它的产品数组与图像一起传递到 Products 组件中
function App() {
const products = [
{
id: 1,
img: { internet },
heading: "Access a private marketplace",
desc:
"Product Description.",
},
];
return (
<main>
<Products products={products} />
</main>
);
}
产品.tsx:
```
type Product = {
id: number;
img: any; // unsure about type, "string" didn't work so i chose "any"
heading: string;
desc: string;
};
type ProductsProps = {
products: Product[];
};
const Products = ({ products }: ProductsProps) => {
return (
<div>
{products.map((product, id) => (
<div>
id: {product.id}
img: <img src={product.img} alt={product.img} />
heading: {product.heading}
desc: {product.desc}
</div>
))}
</div>
);
};
export default Products;
当我运行这个时,alt 标签返回[object Object]
```
我猜你也无法正确显示你的图像。 问题在于您在App.tsx中声明产品数组的方式。
在第 6 行, img
的类型是一个 object,唯一的键是: inte.net
,例如:
const projectImg = {
internet: "link.to.your.image.svg"
}
这会阻止您的Products
组件正确呈现图像,因为<img/>
标记期望product.img
是一个字符串。
用以下代码替换您的产品定义,它应该可以正常运行。
import internet from "./assets/internet.svg";
const products = [
{
id: 1,
img: internet, // notice the lack of curly braces
heading: "Access a private marketplace",
desc: "Product Description.",
},
];
建议一: img: { inte.net }
意思是img: { inte.net: inte.net }
。 你的类型期待img: inte.net
建议 2 :假设您只希望 SVG 是您的图像,那么 SVG 也是元素,因此您可以直接使用它们而无需像下面这样的 IMG 标签。
<div>
id: {product.id}
img: {product.img}
heading: {product.heading}
desc: {product.desc}
</div>
如果您想输入 SVG 图像属性,您可以参考https://stackoverflow.com/a/63165963/14362614
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.