javascript - Css 过渡不适用于 React 中的条件渲染

我有一个简单的复选框,我想使用 React 显示和隐藏一个 div 以及一些过渡延迟。我可以在不使用 React 时达到相同的效果。但是,当我使用条件渲染来 react 以在单击复选框时渲染 div。它没有显示效果。 这是我到目前为止的代码

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

export default function App() {
  const [checkBox, setCheckBox] = useState(false);
  return (
    <div className="App">
      <input
        type="checkbox"
        checked={checkBox}
        onChange={() => setCheckBox(!checkBox)}
      ></input>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      {checkBox && (
        <div
          style={{
            opacity: 1,
            transition: "height 2s",
            transitionTimingFunction: "ease-in"
          }}
        >
          Hey the checkbox is checked
        </div>
      )}
    </div>
  );
}

Codesandbox 链接 - https://codesandbox.io/s/reverent-cartwright-gk11s?file=/src/App.js:0-659

非常感谢任何帮助

最佳答案

它对我有用。 像这样尝试。

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

export default function App() {
  const [checkBox, setCheckBox] = useState(false);
  return (
    <div className="App">
      <input
        type="checkbox"
        checked={checkBox}
        onClick={() => setCheckBox(!checkBox)}
      ></input>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <div className={checkBox ? "animate show" : "animate"}>
        Hey the checkbox is checked
      </div>
    </div>
  );
}

在css文件中...

.animate {
  height: 0px;
  overflow: hidden;
  transition: height 0.5s;
}
.show {
  height: 18px;
}

请在此确认。

https://codesandbox.io/s/goofy-moon-ipe7t

https://stackoverflow.com/questions/67002377/

相关文章:

javascript - 如果没有 .js 扩展名,则为 ERR_MODULE_NOT_FOUND

java - 未找到 native micronaut 数据插入查询的可能实现

google-apps-script - 在多个工作表中搜索一个词

mongodb - 如何在 Rust 中使用 Mongodb::cursor?

azure - Get-AzRoleAssignment 在 Azure Runbook 中引发 M

python - 如何使 Prophet 的输出静音?

typescript - 类型错误 : Property 'currentTime' does no

azure - 对于高级、低延迟、带有搜索功能的大量小型 json 文件,Azure BlockBl

python - datetime.combine with timezone 不同于 dateti

sql-server - SQL 服务器 : splitting a row into severa