首页 > 解决方案 > 如何在点击反应时隐藏div

问题描述

我有一个 divx我需要隐藏整个 div 点击x。我使用钩子 useState()。

.noShow {
  display: none;
}    

  const [showed, setShowed] = useState(false)
  const hideNav = () => { 
      setShowed(true)
  } 
          <div className={ showed ? 'noShow' : ''} className='d-flex justify-content-between align-center pl-2 pr-2'>
             <h6>this is div</h6>
             <h6 onClick={hideNav}>x</h6>
          </div>

如果我设置显示 - 最初它是隐藏的,但是当我点击它时x它不起作用。

标签: javascriptreactjsreact-hooks

解决方案


好吧,当您单击隐藏时,您应该调用一个函数。试试这样。

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [showed, setShowed] = useState(false);
  return (
    <div
      style={showed ? { display: "none" } : { display: "block" }}
      className="d-flex justify-content-between align-center pl-2 pr-2"
    >
      <h6>this is div</h6>
      <h6 onClick={(e) => setShowed(true)}>hide</h6>
    </div>
  );
}

你可以在这里确认。 https://codesandbox.io/s/thirsty-shadow-kz1mp?file=/src/App.js


推荐阅读