使用TailwindCSS设置背景封面,我在useEffect中从bookId(10位数字)中提取了颜色。颜色得到更新,并且组件使用更新后的颜色值重新渲染,但渲染页面的背景颜色仍然是其父div的相同颜色。
const colors = [
'from-red-500',
'from-orange-500',
'from-yellow-500',
'from-green-500',
'from-cyan-500',
'from-blue-500',
'from-indigo-500',
'from-violet-500',
'from-purple-500',
'from-pink-500',
]
function BgCover(props) {
const [color, setColor] = useState(null)
const router = useRouter()
useEffect(() => {
const id = router.query.bookId
const index = id.slice(-1) //从bookId中提取索引
const bgColor = colors[index]
setColor(bgColor)
}, [])
return (
<Fragment>
{color ? (
<div className='flex-grow scrollbar-hide select-none relative'>
<div className={`bg-gradient-to-b ${color} to-black`}>
<section
className={`flex flex-col md:flex-row items-center justify-center p-4`}>
{props.children}
</section>
</div>
</div>
) : (
<p className='text-2xl'>加载中..</p>
)}
</Fragment>
)
}
但是,当我用颜色值(比如'from-red-500')替换color变量时,渲染页面中的背景颜色是可见的。
我还尝试用getStaticProps替换useEffect中的setColor代码,但静态版本的代码无法解决这个问题(当使用color变量时)。
感谢任何帮助。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号