【发布时间】:2019-12-16 11:05:14
【问题描述】:
当我将鼠标悬停在我的 div 上时,我希望我的 className 发生变化。如果我控制台记录状态,它会根据鼠标的位置从真变为假。当我尝试将它与三元运算符一起使用时,它总是将自身设置为 false?
import React, { useState } from 'react';
function NavigationBar() {
const [hover, setHover] = useState({hover: false})
const noHovering = 'flex flex-row bg-white'
const hovering = 'flex flex-row bg-black'
return (
<div className='h-screen max-h-screen w-1/6 float-left shadow-2xl flex flex-col' style={{backgroundColor: '#2b2b2b'}}>
<div className='h-20 flex justify-center items-center' style={{backgroundColor:'#202020'}}>
<h1 className='text-white items-center font-hairline tracking-widest text-lg'>{hover === true ? "NOT WOKRING" : 'PREVENTION ADMIN'}</h1>
</div>
<div className='pl-4 h-full flex flex-col justify-around'>
<div className= {hover ? hovering : noHovering} onMouseOver={() => setHover({hover:true})} onMouseLeave={() => setHover({hover:false})}>
<img src={require('../../images/analysis-gray.png')} alt='analysis' className='mr-5 w-6'/>
<h5 className='antialiased' style={{color:'#c8c8c8'}} >Insights</h5>
</div>
【问题讨论】:
-
我认为您以错误的方式初始化您的状态。试试这个 -
const [hover, setHover] = useState(false)
标签: javascript reactjs state ternary