【问题标题】:How to apply classList.toggle("active") in reactjs如何在 reactjs 中应用 classList.toggle("active")
【发布时间】:2022-02-10 23:57:30
【问题描述】:

如何在 reactjs 中应用classList.toggle("active")。 我创建了两个按钮并提供onclick 函数togglePopup 并在顶部定义它。但我很困惑如何在反应中应用document.getElementById('popup-1').classList.toggle("active")。我在 javaScript 中应用了这个方法,但我不知道它在 react 中是如何工作的?

Popup.jsx

const Filter = () => {
    const togglePopup = () => {
    document.getElementById('popup-1').classList.toggle("active")
    }
    return (
        <>
<button className='p-3 border bg-blue-400'>click</button>
            <div className="popup" id="popup-1">
                <div className="overlay"></div>
                <div className="content">
                    <div className="close-btn" onClick={togglePopup}>&times;</div>
                    <h1 className='text-2xl font-bold'>title</h1>
                    <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Non debitis officia neque nostrum, perspiciatis sed quaerat veritatis numquam, explicabo dolorum aliquam illo dolor at nemo maxime consequatur facilis magni laudantium! Ipsa eveniet quam, illum quos laudantium a placeat temporibus dolores libero pariatur quibusdam atque impedit magnam nam ipsum, rerum sapiente?</p>
                </div>
            </div>

Popup.css

.popup .overlay{
    position: fixed;
    top: 0px;
    left: 0px;
    width: 100vw;
    height: 100vh;
    background:rgba(0, 0, 0, 0.7);
    z-index: 1;
    display: none;
}
.popup .content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) scale(0);
    background: #fff;
    width: 450px;
    height: fit-content;
    z-index: 2;
    text-align: center;
    padding: 20px;
    box-sizing: border-box;
}

.popup .close-btn{
    position: absolute;
    right: 20px;
    top: 20px;
    width: 30px;
    height: 30px;
    background: #222;
    color: #fff;
    font-size: 25px;
    font-weight: 600;
    line-height:30px;
    text-align:center;
    border-radius: 50%;
    cursor: pointer;
}

.popup:active .overlay{
    display: block;
}
.popup:active .content{
    transition: all 300ms ease-in-out;
    transform: translate(-50%, -50%) scale(1);

}

【问题讨论】:

  • 通常,您不应该使用 React 手动操作 DOM。您可以定义 state 并在单击时切换状态。然后如果状态为true,则在 attr 中包含所需的类名。
  • 这能回答你的问题吗? Toggle Class in React

标签: javascript css reactjs


【解决方案1】:

您不应该从 React 查询或操作 DOM。如果您想切换一个类,请让您的按钮更新组件的状态,然后根据该状态呈现标记。

function MyComponent () {
  const [active, setActive] = useState(false);

  return (
    <div className={active ? 'active' : ''}>
      <button onClick={() => setActive(!active)}>Toggle</button>
    </div>
  )

}

【讨论】:

    猜你喜欢
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 2021-02-14
    • 2021-03-30
    • 1970-01-01
    • 2021-06-24
    相关资源
    最近更新 更多