React 文本在状态变化时淡入 - 对象

React Text Fade In on State Change - Object

我想在 React 中为一些文本制作动画,根据商店中值的变化对文本对象进行淡出和淡入。我在想像 useEffect 这样依赖于所述商店的东西可以解决这个问题,但我不确定如何去实现它。

我想要设置动画的值是下面代码中的 {selection.price.toFixed(2)}。每当 markets 发生变化时,我希望新文本在状态变化期间淡出并在短时间内突出显示:

export const MatchPrices = () => {
  const markets = useStore($markets);

  const updateNotificationRef = useRef();

  useEffect(() => {
 
    if (markets.length === 0) {
      return;
    }

    updateNotificationRef.current.animate(
      {
        opacity: [0, 1, 0],
      },
      1000
    );
  }, [markets]);

  return (
    <Card className="price-display">
      <Table className="card-table prices-table" size="sm">
        <thead className="card-header">
          <tr>
            <th>Home</th>
            <th>Draw</th>
            <th>Away</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            {markets.length !== 0 ? (
              markets
                .filter((market) => market.mt === "MATCH_WINNER")[0]
                .selections.map((selection) => (
                  <td
                    className="match-price"
                    key={selection.id}
                    ref={updateNotificationRef}
                    style={{ opacity: 1 }}
                  >
                    {selection.price.toFixed(2)}
                  </td>
                ))
            ) : (
              <td>
                <Spinner
                  animation="border"
                  role="status"
                  style={{
                    marginLeft: "Auto",
                    marginRight: "Auto",
                  }}
                ></Spinner>
              </td>
            )}
          </tr>
        </tbody>
      </Table>
    </Card>
  );
};

虽然我不太确定如何让 CSS 工作。

一个使用网络动画的例子:

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

export default function App() {
  const initialState = 0;
  const [count, setCount] = useState(initialState);
  const updateNotificationRef = useRef();

  useEffect(() => {
    // Skipping the initial render. TODO: use a better solution from 
    if (count === initialState) {
      return;
    }
    updateNotificationRef.current.animate(
      {
        opacity: [0, 1, 0]
      },
      500
    );
  }, [count]);

  return (
    <div>
      <button onClick={() => setCount((c) => c + 1)} children="Increment" />
      <div ref={updateNotificationRef} style={{ opacity: 0 }}>
        Updated
      </div>
    </div>
  );
}

现场演示:codesandbox.io