admin管理员组文章数量:1405563
I'm struggling to understand how I can pass through JS variable into className like:
<img className="pos-1 speed-${Math.floor(Math.random() * 10) + 1}" src={Onion1} />
where {Math.floor(Math.random() * 10) + 1}
will set a range number so that I can add classes randomly for speed-1 speed-2 etc.
console.log(`pos-1 speed-${Math.floor(Math.random() * 10) + 1}.`);
<img className=`pos-1 speed-${Math.floor(Math.random() * 10) + 1}.` src={Onion1} />
Can anyone help?
Also tried:
const classes = () => {
return `pos-${Math.floor(Math.random() * 10) + 1} speed-${Math.floor(Math.random() * 10) + 1}.`;
}
<img className={classes} src={Onion1} />
I'm struggling to understand how I can pass through JS variable into className like:
<img className="pos-1 speed-${Math.floor(Math.random() * 10) + 1}" src={Onion1} />
where {Math.floor(Math.random() * 10) + 1}
will set a range number so that I can add classes randomly for speed-1 speed-2 etc.
console.log(`pos-1 speed-${Math.floor(Math.random() * 10) + 1}.`);
<img className=`pos-1 speed-${Math.floor(Math.random() * 10) + 1}.` src={Onion1} />
Can anyone help?
Also tried:
const classes = () => {
return `pos-${Math.floor(Math.random() * 10) + 1} speed-${Math.floor(Math.random() * 10) + 1}.`;
}
<img className={classes} src={Onion1} />
Share
Improve this question
edited Apr 8, 2022 at 17:15
lky
asked Apr 8, 2022 at 17:07
lkylky
1,1293 gold badges18 silver badges38 bronze badges
1
- 1 Does this answer your question? How to dynamically add a class to manual class names? – Stucco Commented Apr 8, 2022 at 17:10
1 Answer
Reset to default 8Your last attempt is very close, you just forgot to enclose it in {...}
:
className={`pos-1 speed-${Math.floor(Math.random() * 10) + 1}`}
Any values passed as attributes/props in React that are not simple string literals need to be enclosed in {...}
.
本文标签: reactjsHow to add javascript variable within classNamereact jsStack Overflow
版权声明:本文标题:reactjs - How to add javascript variable within className - react js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744338854a2601354.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论