如何修复此代码以在React中正确过渡

时间:2019-06-08 20:28:37

标签: javascript css reactjs

我正在努力使用此过渡库,尤其是因为我不希望装入状态依赖于传递给props的值,并且想知道如何利用该库来获得所需的简单褪色行为切换卡时或如果有人可以推荐可用的库时,请进进出出:https://codesandbox.io/s/gifted-breeze-v638p

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import { Transition } from "react-transition-group";

import "./styles.css";
const duration = 3000;
const defaultStyle = {
  transition: `opacity ${duration}ms ease-in-out`,
  opacity: 0
};

const transitionStyles = {
  entering: { opacity: 1 },
  entered: { opacity: 1 },
  exiting: { opacity: 0 },
  exited: { opacity: 0 }
};
const Card = ({ txt }) => {
  const [hasChanged, setHasChanged] = useState(false);
  useEffect(() => {
    console.log("mounting...");
    setHasChanged(false);
    setTimeout(() => setHasChanged(true), 0);
    return () => {
      console.log("unmounting...");
    };
  }, [txt]);
  return (
    <Transition in={hasChanged}>
      {state => {
        console.log("state >>", state);
        return (
          <div
            style={{
              ...defaultStyle,
              ...transitionStyles,
              display: "flex",
              justifyContent: "center",
              alignItems: "center",
              backgroundColor: "aqua",
              height: "500px"
            }}
          >
            {txt}
          </div>
        );
      }}
    </Transition>
  );
};

function App() {
  const [card, setCard] = useState(0);
  const options = ["foo", "bar", "baz"];
  return (
    <div className="App">
      <div>
        <header>Click one</header>
        {options.map((op, i) => (
          <div
            onClick={() => setCard(i)}
            style={{ background: "pink", margin: "3px" }}
          >
            {op}
          </div>
        ))}
      </div>
      <Card txt={options[card]} />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

0 个答案:

没有答案