如何使用react spring在onClick事件上设置文本动画



所以,我使用NextJs和React spring来制作一个;随机报价机";(我之前完成了一个免费代码营挑战,但我只想尝试新的东西,例如使用nextjs和react spring动画(

所以一切都很好,但当我点击";新报价"按钮,它将生成一个带有淡入动画的新引用,而当我单击按钮时它不会。它只在第一次加载页面时工作。

对此有什么变通办法吗?我也使用了chakraUI,但它没有各种动画或过渡。我的沙箱链接:https://codesandbox.io/s/compassionate-heisenberg-byulo?file=/pages/index.js

以下是我迄今为止写的代码:

import * as React from "react";
import { useState, useCallback } from "react";
import {
ChakraProvider,
Box,
Text,
Button,
Icon,
Flex,
HStack,
Heading,
Link
} from "@chakra-ui/react";
import { FaTwitter, FaQuoteLeft } from "react-icons/fa";
import quoteArray from "../pages/day/quotes";
import { useSpring, animated } from "react-spring";
const Title = () => {
return (
<Box>
<Heading mt="1%" align="center">
Random Quote Generator
</Heading>
</Box>
);
};
const QuoteBox = () => {
const [loading, setLoading] = useState(true);
const [quote, setQuote] = useState(null);
const props = useSpring({
from: { opacity: 0 },
to: { opacity: 1 }
});
const onQuoteChange = useCallback(() => {
setLoading(true);
const randomQuote =
quoteArray[Math.floor(Math.random() * quoteArray.length)];
setLoading(false);
setQuote(randomQuote);
}, []);
React.useEffect(() => {
onQuoteChange();
}, [onQuoteChange]);
return (
<Box>
<Title />
<Box
width="50%"
height="100%"
border="1px"
boxShadow="md"
p={5}
rounded="md"
bg="white"
borderColor="gray.400"
mx="auto"
my="10%"
>
<Box>
<Flex>
<Box>
<Icon as={FaQuoteLeft} w={7} h={6} />
<animated.div style={props}>
<Text fontSize="2xl">
{loading || !quote ? "..." : quote.quote}
</Text>
</animated.div>
</Box>
</Flex>
</Box>
<Box>
<animated.div style={props}>
<Text fontSize="xl" align="right">
-{loading || !quote ? "..." : quote.author}
</Text>
</animated.div>
</Box>
<HStack mt="2%" ml="1%" spacing="2%">
<Button colorScheme="blue" size="sm" onClick={onQuoteChange}>
New Quote
</Button>
<Button
as={Link}
colorScheme="twitter"
size="sm"
leftIcon={<FaTwitter />}
target="_blank"
href="https://twitter.com/intent/tweet?text=Hello%20world"
>
Twitter
</Button>
</HStack>
</Box>
</Box>
);
};
function App() {
return (
<ChakraProvider>
<QuoteBox />
</ChakraProvider>
);
}
export default App;

如果在每个新引号上使用set方法重置spring配置,则动画应该可以工作。

试试这个分叉沙盒https://codesandbox.io/s/competent-rgb-umgx5?file=/pages/index.js

更改1

const states = [
{
config: { duration: 1250 },
from: { opacity: 0.2, color: "green" },
to: { opacity: 0.6, color: "red" }
},
{
config: { duration: 1250 },
from: { opacity: 0.2, color: "red" },
to: { opacity: 0.6, color: "green" }
}
];

更改2(更改useSpring的用法(

const [toggle, setToggle] = useState(false);
const [props, set] = useSpring(() => ({
...states[+toggle]
}));

更改3(更新newQuote回调以调用set(

onClick={() => {
onQuoteChange();
set({
...states[+!toggle]
});
setToggle(!toggle);
}}

最新更新