[英]How can I show dynamic images with require() in React Native?
我正在從 api 獲取數據,然后我想根據來自 api 數據的符號顯示圖像
{apiData ? (
apiData.data.map((item, key) => (
<Listing symbol={item.symbol} path={`../images/${item.symbol}.png`} />
))
) : (
<></>
)}
將路徑和符號發送到另一個組件 VVVV
const Listing = ({ symbol, path }) => {
return (
<View style={tw`flex-row justify-between p-10`}>
<View style={tw`flex-row items-center`}>
<Text style={tw`mr-2`}>{symbol}</Text>
<Image source={require(path)} style={{ width: 50, height: 50 }} />
<Text>{path}</Text>
</View>
</View>
);
};
有沒有辦法做到這一點,或者我必須使用別的東西?
“為了使其工作,必須靜態知道require
中的圖像名稱”,這就是 React Native 的文檔所說的。 換句話說,你不能要求 React Native 中的圖像具有動態路徑。
在您的情況下,解決方法是將它們靜態導入到 object 中,其中每個鍵是一個symbol
,其值是其相關圖像的path
。 不要忘記使用正確的路徑:
const images = {
one: require("../images/imageOne.png"),
two: require("../images/imageTwo.png"),
};
這樣,您只需Listing
symbol
,它將從上面的 object 中獲取圖像:
const Listing = ({ symbol }) => {
return (
<View style={tw`flex-row justify-between p-10`}>
<View style={tw`flex-row items-center`}>
<Text style={tw`mr-2`}>{symbol}</Text>
<Image source={images[symbol]} style={{ width: 50, height: 50 }} />
<Text>{path}</Text>
</View>
</View>
);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.