在React Native中构建动画挂钩
注意:在记录/写入时,React Native 0.59处于RC状态。 因此,要试用它,您需要指定您的React Native版本react-native init MyProject --version react-native@next
第二注:钩子是新的,我也是新手。 我可能在视频中多次认错-抱歉! 我也在学习他们😉
这篇文章最初发表在React Native School上。 有关最新文章和资源,请在那里访问我! 另外,如果您希望升级为React Native开发人员,请查看我们的其他一些教程!
为什么要使用Ref?
我在此代码中使用useRef
的原因是由于文档中的这一行:
返回的对象将在组件的整个生存期内持续存在。
因为我们想要一个不断更新的动画值,所以我们希望它在组件的整个生命周期中保持不变,而不是在每次组件更新时重新创建(在这种情况下,每次计数都会递增)。
更新#1:避免内存泄漏
请查看下面的代码。 为避免内存泄漏,您需要清理卸载组件时的超时。 您可以通过从useEffect
回调返回一个函数(在其中调用clearTimeout
来实现此目的。 感谢Milli指出这一点!
其他资源
- 了解有关React Hooks的更多信息。
- useEffect挂钩
- useRef挂钩
视频的最终代码可以在下面找到:
import React, { useEffect, useRef } from 'react';
import { View, Animated, Text } from 'react-native';
const Box = ({ backgroundColor = '#3cae6f', scale = 1 }) => (
<Animated.View
style={[
{
width: 100,
height: 100,
backgroundColor,
transform: [{ scale }],
},
]}
/>
);
const usePulse = (startDelay = 500) => {
const scale = useRef(new Animated.Value(1)).current;
const pulse = () => {
Animated.sequence([
Animated.timing(scale, { toValue: 1.2 }),
Animated.timing(scale, { toValue: 0.8 }),
]).start(() => pulse());
};
useEffect(() => {
const timeout = setTimeout(() => pulse(), startDelay);
return () => clearTimeout(timeout);
}, []);
return scale;
};
const App = ({ count }) => {
const scale = usePulse();
const scale2 = usePulse(750);
return (
<View
style={{ flex: 1, alignItems: 'center', justifyContent: 'space-around' }}
>
{count}
);
};
// class App extends React.Component {
// scale = new Animated.Value(1);
// componentDidMount() {
// setTimeout(() => this.pulse(), 500);
// }
// pulse = () => {
// Animated.sequence([
// Animated.timing(this.scale, { toValue: 1.2 }),
// Animated.timing(this.scale, { toValue: 0.8 }),
// ]).start(() => this.pulse());
// };
// render() {
// return (
//
// {this.props.count}
//
//
// );
// }
// }
export default class Wrapper extends React.Component {
state = { count: 1 };
componentDidMount() {
setInterval(() => {
this.setState(state => ({
count: state.count + 1,
}));
}, 500);
}
render() {
return ;
}
}