可以使用一个状态变量来控制展开和折叠。在状态变量为true时,将Animated.View组件包裹在一个View组件中,在View组件的style中设置高度为固定值。在状态变量为false时,将View组件的高度设置为0,实现折叠效果。以下是一个例子:
import React, { useState } from 'react';
import { View, Animated, Button } from 'react-native';
const ExpandingComponent = () => {
const [isExpanded, setExpanded] = useState(false);
const heightAnimation = new Animated.Value(0);
const toggleExpansion = () => {
setExpanded(!isExpanded);
if (isExpanded) {
Animated.timing(heightAnimation, {
toValue: 0,
duration: 200,
useNativeDriver: false,
}).start();
} else {
Animated.timing(heightAnimation, {
toValue: 100,
duration: 200,
useNativeDriver: false,
}).start();
}
};
return (
<>
// add content here
>
);
};
上一篇:Animated.View样式未随着动画变量的更新而改变
下一篇:Animated: `useNativeDriver`未指定。这是一个必需的选项,必须明确设置为`true`或`false`在React Native上。