如何在React中为动态生成的类应用Tailwind过渡效果?
Great question! Getting smooth transitions working with dynamically swapped Tailwind classes is totally doable—let's walk through exactly what you need to adjust:
Key Steps to Make This Work
Tailwind doesn't automatically apply transitions to every property, so we need to explicitly define what we want to animate, plus add the easing and duration utilities. Here's how to tweak your code:
Specify the transition property
Theitems-endanditems-startclasses modify the CSSalign-itemsproperty, which isn't one of Tailwind's default transition targets. We'll use a custom transition class to target it directly:transition-[align-items].Add easing and duration utilities
Throw inease-in(orease-out/ease-in-outdepending on the curve you want) and aduration-*class (likeduration-300for a 300ms transition) to control the animation's speed and feel.Confirm JIT mode is active
Lucky for you, Tailwind v3 enables JIT mode by default. This means it can scan your ternary operator and recognize bothitems-endanditems-startas valid classes, so it won't purge them from your CSS build.
Modified Code Example
import { useState } from 'react'; function YourComponent() { const [isLarge, setIsLarge] = useState(true); return ( <div className={`w-5 h-5 flex flex-col justify-around ${isLarge ? 'items-end' : 'items-start'} cursor-pointer transition-[align-items] ease-in duration-300 `} onClick={() => setIsLarge((prev) => !prev)} /> ); }
Extra Tips
- If you're animating multiple properties (like alignment and width), swap
transition-[align-items]withtransition-allto animate all animatable CSS properties at once. - Play around with different duration values (e.g.,
duration-200for faster,duration-700for slower) or easing functions to get the exact feel you want.
内容的提问来源于stack exchange,提问作者Amos Machora

