英文:
Dynamic img src
问题
I understand your request. Here's the translated code portion:
<img src={`Avatar${user_id % 3}`}/>
If you have any more code to translate, please provide it, and I'll assist you further.
英文:
Alright, so I have 3 different Avatars that I want to be randomly assigned to users but constantly so for each user, what I decided was best is to modulus the user id by 3 and set to whatever that is, so this is the code
<img src={`Avatar${user_id % 3}`}/>
However, the src is being parsed as a string, rather than a reference to my imported Avatar3
To clarify, the result I'd like is what would be normally coded as
<img src={Avatar3} />
But what I'm getting is what would be coded as <img src="Avatar3" />
How can I fix this? thanks!
答案1
得分: 1
你可以创建一个图片映射并引用它。
const imageMap = {
1: Avatar1,
2: Avatar2,
3: Avatar3,
}
<img src={imageMap[user_id % 3]}/>
英文:
You can create a imageMap and reference that.
const imageMap = {
1: Avatar1,
2: Avatar2,
3: Avatar3,
}
<img src={imageMap[user_id % 3]}/>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论