状态更改时的反应文本淡入-对象



我想在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 https://stackoverflow.com/questions/53179075/with-useeffect-how-can-i-skip-applying-an-effect-upon-the-initial-render
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

最新更新