试着把我的头围绕什么过程将是改变一个图像源取决于从数据库返回的值。
片段:
function KnifesComponent() {
const knifeCollection = collection(db, "knives");
const [knives, setKnives] = useState([]);
useEffect(() => {
onSnapshot(knifeCollection, (snapshot) => {
setKnives(snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
});
}, []);
return (
{knives.map((skin) => {
return (
{skin.rarity} // Returns "Ultra" for Example
<div><img src={isUltra : require('../../public/Rarity_Ultra.png')}></div>
);
}
我正在考虑用所有的值做一个const,然后根据需要使用,但不确定如何接近它
const rarities = {
Exclusive: require('../../public/Rarity_Exclusive.png'),
Ultra: require('../../public/Rarity_Ultra.png'),
}
根据值有条件地格式化不同图像的正确方法是什么?
您可以将稀有性对象更改为(路径作为值):
const rarities = {
Exclusive: '../../public/Rarity_Exclusive.png',
Ultra: '../../public/Rarity_Ultra.png',
}
然后您可以通过稀有性访问对象中的图像。
function KnifesComponent() {
const knifeCollection = collection(db, "knives");
const [knives, setKnives] = useState([]);
useEffect(() => {
onSnapshot(knifeCollection, (snapshot) => {
setKnives(snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
});
}, []);
return (
{
knives.map((skin) => {
return (
{skin.rarity} // Returns "Ultra" for Example
<div>
<img src={require(rarities[skin.rarity])}>
</div>
);
})
}
);
}
对象也可以像这样(只是图像名称):
const rarities = {
Exclusive: 'Rarity_Exclusive.png',
Ultra: 'Rarity_Ultra.png',
}
并访问它们:
<img src={require(`../../public/${rarities[skin.rarity]}`)}>