简体   繁体   English

使用 React 在 Tailwind 上出现任意值的问题

[英]Problem with arbitrary values on Tailwind with React

I'm trying to make a react component that changes the width from a parameter but it's doesn't work and I don't know why.我正在尝试制作一个反应组件来改变参数的宽度,但它不起作用,我不知道为什么。

function Bar() {
    
    const p =80

    const style = `bg-slate-500 h-8 w-[${p.toFixed(1)}%]`

    console.log(style)

    return (
        <div className=' h-8 w-full'>
            <div className={`bg-slate-500 h-8 w-[${p}%]`}>
            </div>
        </div>
    )
}
export default Bar

With this code I get a full-size bar, but if I use a strict String with 80.0 it works fine使用此代码,我得到一个全尺寸条,但如果我使用 80.0 的严格字符串,它可以正常工作

The other answers are wrong.其他答案都是错误的。 In Tailwind V3 JIT is included and you won't need to set mode to jit anymore.在 Tailwind V3 中包含 JIT,您不再需要将模式设置为 jit。 And even in Tailwind V2 the posted code wouldn't work.即使在 Tailwind V2 中,发布的代码也不起作用。

The actual solution as @Dennis Martinez mentioned in a comment is to move truly dynamic styles out of the classes and to inline styles . @Dennis Martinez 在评论中提到的实际解决方案是将真正动态的 styles 移出类并inline styles

This is wrong :这是错误的:

const padding = 80;
<div className=`p-[${padding}%]`>
  Some Content
</div>

Instead use inline styling :而是使用inline styling

const padding = 80;
<div style={{padding: `${padding}%`}}>
  Some Content
</div>

Include mode: 'jit' in tailwind config file包含模式:tailwind 配置文件中的“jit”

in tailwind.config.js add mode: 'jit' .tailwind.config.js添加mode: 'jit'

I would suggest https://v2.tailwindcss.com/docs/just-in-time-mode to learn more.我建议https://v2.tailwindcss.com/docs/just-in-time-mode了解更多信息。

eg:例如:

module.exports = {
   //other options
   mode: 'jit',
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM