react-native - 反应相互影响的原生动画组件
问题描述
语境:
我有一个名为的组件AnimatedSlider
,它在App.js
.
AnimatedSlider
用于React.Animated
为其中 a 的宽度设置动画View
。这是代码。
AnimatedSlider.js
import React, { useRef } from 'react';
import {
Text,
View,
StyleSheet,
TouchableWithoutFeedback,
Animated,
Easing,
} from 'react-native';
const { Value } = Animated;
const MENU_ITEM_WIDTH = 50;
const MENU_ITEM_FINAL_WIDTH = 200;
const sliderWidthAnimatedValue = new Value(MENU_ITEM_WIDTH);
export default function AnimatedSlider() {
const sliderState = useRef(-1);
const animateExpantion = () => {
Animated.timing(sliderWidthAnimatedValue, {
toValue: MENU_ITEM_FINAL_WIDTH,
duration: 250,
easing: Easing.linear,
useNativeDriver: false,
}).start();
};
const animateCollapse = () => {
Animated.timing(sliderWidthAnimatedValue, {
toValue: MENU_ITEM_WIDTH,
duration: 250,
easing: Easing.linear,
useNativeDriver: false,
}).start();
};
const animateSlider = () => {
if (sliderState.current === -1) {
animateExpantion();
sliderState.current = 1;
} else {
animateCollapse();
sliderState.current = -1;
}
};
return (
<View style={styles.container}>
<Text>Label</Text>
<TouchableWithoutFeedback onPress={animateSlider}>
<Animated.View
style={[styles.slidingMenu, { width: sliderWidthAnimatedValue }]}
/>
</TouchableWithoutFeedback>
</View>
);
}
const styles = StyleSheet.create({
container: {
width: '100%',
height: 50,
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingLeft: 24,
marginBottom: 10,
backgroundColor: 'grey',
},
slidingMenu: {
height: '100%',
width: MENU_ITEM_WIDTH,
backgroundColor: 'pink',
},
});
App.js
import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
import AnimatedSlider from './components/AnimatedSlider';
export default function App() {
return (
<View style={styles.container}>
<AnimatedSlider menuColor='pink'/>
<AnimatedSlider menuColor='pink'/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
});
问题:单击一个组件似乎也会为另一个组件设置动画。
你可以看看这里的小吃
解决方案
问题在于下一行的位置。
const sliderWidthAnimatedValue = new Value(MENU_ITEM_WIDTH);
在组件内移动它解决了这个问题。原因是实例,Value
因此slideWidthAnimatedValue
在组件实例之间共享AniatedSlider
。
推荐阅读
- php - 将文本添加到标签元素搜索栏 Wordpress
- javascript - 需要帮助了解闭包
- php - 用于显示 id 大于 4 的每个类别的最大视图的 sql 代码
- angular - 使用 FormControlName 作为选择器聚焦
- sql-server - 查找列值链 - 跟进
- ios - 更改时间后奇怪的NSDate
- mongodb - 多个 orOperator 的条件查询抛出限制错误
- ios - 如何在一个手势期间禁用/启用 UITableView 中的滚动(iOS - Swift)
- python - SQLAlchemy 引擎结果代理错误(Flask Python)
- c# - 根据另一列中包含的文本保存数据