【问题标题】:Css transition not working on conditional rendering in ReactCss 过渡不适用于 React 中的条件渲染
【发布时间】:2021-07-04 05:28:51
【问题描述】:

我有一个简单的复选框,我想使用 React 显示和隐藏一个 div 以及一些转换延迟。不使用 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>
  );
}

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

非常感谢任何帮助

【问题讨论】:

    标签: javascript html css reactjs animation


    【解决方案1】:

    它对我有用。 试试这样。

    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

    【讨论】:

      猜你喜欢
      • 2021-08-05
      • 1970-01-01
      • 2021-07-14
      • 1970-01-01
      • 1970-01-01
      • 2015-01-02
      • 2015-11-01
      • 1970-01-01
      • 2021-08-09
      相关资源
      最近更新 更多