我正在尝试为向下滑动到其实际高度的View盒制作动画。首先,如果视图的最大高度(即查看所有内容所需的高度)小于70,则无需动画。如果最大高度大于70,则将说明高度设置为70,然后单击视图时,它将朝最大高度移动。这是我的目标。
由于某种原因,我在使用onLayout函数获取所需的内容高度时遇到了麻烦。这是我的代码:
function card() {
const [expandedDescription, setexpandedDescription] = useState(false);
const [descriptionHeight, setdescriptionHeight] = useState(new Animated.Value(0))
const [layoutCount, setlayoutCount] = useState(0)
const [maxContentHeight, setmaxContentHeight] = useState(0);
const getContentHeight = (event:any) => {
setmaxContentHeight(event.nativeEvent.layout.height);
if(maxContentHeight < 70){
setdescriptionHeight(new Animated.Value(maxContentHeight));
}
else{
setdescriptionHeight(new Animated.Value(70));
}
}
const toggle = () => {
console.log(maxContentHeight);
if(maxContentHeight > 70){
Animated.timing(descriptionHeight, {
toValue: expandedDescription ? descriptionHeight : maxContentHeight,
duration: 300,
}).start();
setexpandedDescription(!expandedDescription);
}
}
return (
<View style={styles.cardContainer}>
<Animated.View style={[styles.descriptionContainer, {height:descriptionHeight}]} onLayout={(event:any) => getContentHeight(event)} >
<Text style={styles.descriptionHeaderText}>Description</Text>
<TouchableOpacity onPress={() => toggle()}>
<Text style={styles.descriptionText}>Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Aenean bibendum tincidfffffffffunt libero, nec luctus dolor consequat
quis. Phasellus portalike elephants and had to work hard to earn their while chicken
</Text>
</TouchableOpacity>
</Animated.View>
</View>
)
}
const styles = StyleSheet.create({
cardContainer: {
width: '95%',
marginBottom: 10,
backgroundColor: '#ffffff',
borderRadius:25,
height: 'auto',
alignItems:'center',
paddingLeft: 10,
paddingRight: 10,
},
descriptionContainer:{
width: '100%',
alignItems:'center',
marginTop: 10,
padding:5
},
descriptionHeaderText:{
fontSize: 15,
color:'#8E8E8E',
},
descriptionText:{
marginTop: 5,
},
});
export default card;
如果我只是将动画设为静态并且不运行onLayout函数,则动画将完美运行。但是我需要获取文本框的高度,因此我知道需要达到的高度,因为我是从数据库中提取该文本的。当我运行名为getContentHeight()的onLayout函数时,它要么在0到maxHeight之间来回跳转,要么就一直保持在0。感谢您的帮助!
答案 0 :(得分:0)
useState是异步的。尝试更改此内容:
const getContentHeight = (event:any) => {
setmaxContentHeight(event.nativeEvent.layout.height);
if(maxContentHeight < 70){
setdescriptionHeight(new Animated.Value(maxContentHeight));
}
else{
setdescriptionHeight(new Animated.Value(70));
}
}
对此:
const getContentHeight = (event:any) => {
const height = event.nativeEvent.layout.height;
setmaxContentHeight(height);
if(height < 70){
setdescriptionHeight(new Animated.Value(height));
}
else{
setdescriptionHeight(new Animated.Value(70));
}
}
此外,我认为动画组件的onLayout工作方式有所不同。
尝试像这样更改onLayout:
<Animated.View
onLayout={Animated.event([
{
nativeEvent: {
layout: {
height: maxContentHeight
}
}
}
])}
/>
,然后使用useEffect(()=> {...},[maxContentHeight])设置描述