带有 React 状态和 FastAverageColor 的 Tailwind CSS 自定义渐变

IT技术 reactjs tailwind-css
2022-07-25 08:36:17

我正在尝试使用 React 状态、Tailwind CSS 和 FastAverageColor 包 ( https://www.npmjs.com/package/fast-average-color ) 在我的 Next JS 应用程序中添加自定义渐变。我为此使用了一个 useEffect 钩子:

const [avgColor, setAvgColor] = useState("")
useEffect(() => {
        const fac = new FastAverageColor()
        fac.getColorAsync(songData.track.album.images[0].url, { algorithm: 'dominant' }).then(result => {
            setAvgColor(`w-full h-full absolute bg-gradient-to-tr from-[${result.hex}] to-transparent`)
        })
}, [avgColor, songData.track.album.images])

JSX 如下所示:

        <div className="relative w-full h-full">
            <Image priority alt="test" layout='fill' objectFit='cover' src={songData.track.album.images[0].url} />
            {avgColor ? <div className={avgColor}></div> : null}
        </div>

问题是我的渐变没有出现在图像上。你知道为什么会这样吗?

1个回答

不能使用 JIT 类,但您可以使用from-current并设置内联颜色来设置起始颜色。

所以,试试这个:

setAvgColor(result.hex)

<div style={{color: avgColor}} className="w-full h-full absolute bg-gradient-to-tr from-current to-transparent"></div>

基本演示