我最近一直在玩 React Native 上的动画,我遇到了react-native-reanimated
and react-native-gesture-handler
。我正在尝试使用水平滚动视图构建进度条,当我单击按钮时,滚动视图会转到请求的位置并且进度条会填充一点。我想要实现的是使用BaseButton
's 或RectButton
'sonPress
并onHandlerStateChange
处理滚动逻辑和动画登录。这是我建立的:
import React, { useRef } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Animated, {
interpolate,
useCode,
cond,
and,
neq,
eq,
Value,
set,
Extrapolate
} from "react-native-reanimated";
import { ScrollView, BaseButton, State } from "react-native-gesture-handler";
import { withTransition } from "react-native-redash";
import ProgressBar from "./src/progressBar";
let index = 0;
const position = new Value(0);
const numbers = [1, 2, 3, 4, 5];
export default function App() {
const state = new Value(State.UNDETERMINED);
const transPosition = withTransition(position);
const scrollRef = useRef();
useCode(() => {
cond(
and(
eq(state, State.END),
neq(position, 1)
),
set(position, position + 0.2)
)
}, [state]);
const scroll = () => {
index++;
if(scrollRef.current && scrollRef.current.scrollTo) {
scrollRef.current.scrollTo({
animated: true,
x: 300 * index,
y: 0
});
}
}
const HandleChange = Animated.event([
{
nativeEvent: { state }
}
])
return (
<View style={styles.container}>
<Text>Progress Bar</Text>
<ProgressBar width={interpolate(transPosition, {
inputRange: [0, 0.2, 0.4, 0.6, 0.8, 1],
outputRange: [0, 50, 100, 150, 200, 250],
extrapolate: Extrapolate.CLAMP
})}/>
<ScrollView
ref={scrollRef}
scrollEnabled={false}
horizontal
pagingEnabled
style={{ width: 300, height: 250 }}
>
{numbers.map(num => (
<View style={styles.page} key={num}>
<Text style={styles.number}>
{num}
</Text>
</View>
))}
</ScrollView>
<BaseButton
onHandlerStateChange={HandleChange}
onPress={scroll}
>
<View accessible>
<Text>
Next
</Text>
</View>
</BaseButton>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 100,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
page: {
flex: 1,
justifyContent: "center",
alignItems: "center",
width: 300
},
number: {
fontSize: 22,
fontWeight: "bold"
}
});
这也是进度条组件:
import React, { memo } from "react";
import { StyleSheet, View } from "react-native";
import Animated from "react-native-reanimated";
function ProgressBar({ width }) {
return (
<View style={styles.ProgressBar}>
<Animated.View style={[styles.absoluteFill, { width }]}></Animated.View>
</View>
);
}
const styles = StyleSheet.create({
ProgressBar: {
height: 22,
borderWidth: 2,
borderColor: "#000",
borderRadius: 10,
width: 200
},
absoluteFill: {
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: "#000",
borderRadius: 5
}
})
export default memo(ProgressBar);
但是,当我单击“下一步”按钮时,会出现此错误: BaseButton 上的错误
我很难解决这个问题,所以我问这个,通过按下按钮来处理动画和 JS 逻辑的最佳/正确方法是什么?如果有人可以帮助我,我将不胜感激。