前言
今天,我写了一个评论区展开动画,利用state控制是否展开评论区,然后犯了一个低级错误,就是state更改后不会立即更新,从而导致动画未能达到理想状态。
错误示范
1. 分别声明一个控制评论区显示的state和控制评论区高度的state(因为后面要用到Animated动画,所以要使用Animated的写法),并分别给一个默认值false和默认值0,也就是默认情况下不展开评论区。
const [showComment, setShowComment] = useState(false);
const [commentHeight] = useState(new Animated.Value(0));
2. 创建一个按钮和评论区盒子
// 按钮
<Pressable style={{position:'absolute',width:50,height:50,right:10,top:10}} onPress={toggleComment}>
<Text>点击打开评论区</Text>
</Pressable>
// 评论区盒子
<Animated.View style={{height:commentHeight,width:'100%',backgroundColor:'white'}}>
{<View>主要内容</View>}
</Animated.View>
3. 创建动画,这里我将评论区高度设置为hp(60),这里的hp(60)就是高度的60%,我是使用了这个库react-native-responsive-screen - npm,因为这样可以提高写代码效率。
然后我的错误就是从此刻开始的,我预想的情况是:点击按钮后调用toggleComment函数,然后利用setShowComment(!showComment); 将showComment变为true,这样下面的Animated的toValue: showComment ? hp(60) : 0 就会使用hp(60)。
但是,state在值更改后并不会立即更新,所以其实在点击按钮后,执行Animated还是false,得需要点击两次按钮才会打开评论区。这样的效果并不理想。
// 先导入动画库
import { Animated } from 'react-native'
// 写切换评论区的函数和动画参数
const toggleComment = () => {
setShowComment(!showComment);
Animated.timing(commentHeight, {
toValue: showComment ? hp(60) : 0, // 控制评论区的高度,如果showComment值为true就高度展开为hp(60),否则就变为0
duration: 500, // 动画持续时间
useNativeDriver: false, // 在 Android 设备上使用 native driver 时可能会出现问题
}).start();
};
解决方案
在声明的时候直接把值设置为true,其他代码依旧
const [showComment, setShowComment] = useState(true);
const [commentHeight] = useState(new Animated.Value(0));