hea*_*y12 1 javascript string var reactjs
我正在努力理解如何将 JS 变量传递到 className 中,例如:
<img className="pos-1 speed-${Math.floor(Math.random() * 10) + 1}" src={Onion1} />
Run Code Online (Sandbox Code Playgroud)
其中{Math.floor(Math.random() * 10) + 1}将设置一个范围编号,以便我可以为 speed-1、speed-2 等随机添加类。
console.log(`pos-1 speed-${Math.floor(Math.random() * 10) + 1}.`);
<img className=`pos-1 speed-${Math.floor(Math.random() * 10) + 1}.` src={Onion1} />
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙吗?
还尝试过:
const classes = () => {
return `pos-${Math.floor(Math.random() * 10) + 1} speed-${Math.floor(Math.random() * 10) + 1}.`;
}
<img className={classes} src={Onion1} />
Run Code Online (Sandbox Code Playgroud)
您的最后一次尝试非常接近,您只是忘记将其包含在{...}:
className={`pos-1 speed-${Math.floor(Math.random() * 10) + 1}`}
Run Code Online (Sandbox Code Playgroud)
在 React 中作为属性/属性传递的任何不是简单字符串文字的值都需要包含在{...}.
| 归档时间: |
|
| 查看次数: |
2701 次 |
| 最近记录: |