三元运算符没有监听本地状态

ternary operator is not listening to local state

我希望在将鼠标悬停在 div 上时更改我的类名。如果我控制台记录状态,它会根据鼠标的位置从真变为假。当我尝试将它与三元运算符一起使用时,它总是将自己设置为 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>

三元运算符始终 returns 为真,因为您正在检查 hover 为真值的实例。

根据您定义州的方式,您必须使用 hover.hover

检查字段 hover
    const [hover, setHover] = useState({hover: false})
    <div 
     className= {hover.hover ? hovering : noHovering} 
     onMouseOver={() => setHover({hover:true})} 
     onMouseLeave={() => setHover({hover:false})}>
    ..
    </div>

或者,也可以切换为布尔值,这样可以使事情变得更简单:

    const [hover, setHover] = useState(false)
    <div 
     className= {hover ? hovering : noHovering} 
     onMouseOver={() => setHover(true)} 
     onMouseLeave={() => setHover(false)}>
    ..
    </div>

hover ? ...总是returnstrue因为是对象{ hover: false },这里不需要对象,把状态改成:

const [hover, setHover] = useState(false)

当你想设置 hover:

setHover(true)
// Or
setHover(false)

如果你想保留它作为一个对象,只需将你的条件更改为:

hover.hover ? hovering : noHovering

我认为没有必要将 hover 状态作为对象然后读取其中的 属性。你可以这样做:-

const [hover, setHover] = useState(false);
const noHovering = 'flex flex-row bg-white'
const hovering = 'flex flex-row bg-black'

<div 
 className= {hover? hovering : noHovering} 
 onMouseOver={() => setHover(true)} 
 onMouseLeave={() => setHover(false)}>
..
</div>

如果要保持当前状态形状,只需使用destructured assignment提取hover 属性:

//     v       v  extract hover property from state 
const [{ hover }, setHover] = useState({hover: false})