使用标志切换类名

toggle className using flag

const [flag, setFlag] = useState(false)

let visibleActive, visibleTransition

const handleSelect = () => {
    setFlag(!flag)
    visibleActive = flag ? 'visible active' : ''
    visibleTransition = flag ? 'visible transition' : ''
    console.log(flag)
    console.log(visibleActive)
    console.log(visibleTransition)
}

return (
    <>
        <div className="ui form">
            <div className="field">
                <label className="label">Select a color</label>
                <div className={`ui selection dropdown ${visibleActive}`} onClick={handleSelect}>
                    <i className="dropdown icon"></i>
                    <div className="text">Select Color</div>
                    <div className={`menu ${visibleTransition}`}>
                    </div>
                </div>
            </div>
            
        </div>
    </>
)

类 单击下拉菜单时不切换。我在控制台中看到了结果,但同样不适用于 JSX。变量 'visibleTransition' 和 'visibleActive' 具有正确的值,但仍未应用这些值。

对 React setState 调用进行批处理、排队和状态更新 may be asyncflag 状态设置后无法立即访问

visibleActivevisibleTransition 变量将在 re-render 后丢失其值。您可以使用 useRef 来保持 re-render 之间的值。

import {useRef} from 'react'

const visibleActive = useRef("")
const visibleTransition = useRef("")

你可以给 ref 赋值,比如 visibleActive.current = flag ? "visible active" : "";

并使用useEffect获得正确的flag状态值

useEffect(() => {
  visibleActive.current = flag ? "visible active" : "";
  visibleTransition.current = flag ? "visible transition" : "";
  console.log(flag);
  console.log(visibleActive);
  console.log(visibleTransition);
}, [flag]);