当我在用户浏览屏幕时实现自定义动画时,我遇到了类型错误。在“堆栈导航器”部分中,同时使用自定义动画的可用属性,即“transitionSpec”
import { Easing, StyleSheet, Text, View } from "react-native";
import Home from "./screens/Home";
import Details from "./screens/Details";
import {
createStackNavigator,
CardStyleInterpolators,
} from "@react-navigation/stack";
import { NavigationContainer } from "@react-navigation/native";
export type RootStackParamList = {
Home: undefined; // No parameters expected for Home screen
Details: undefined;
};
const Config = {
animation: "spring",
config: {
stiffness: 1000,
damping: 50,
mass: 3,
overshootClamping: false,
restDisplacementThreshold: 0.01,
restSpeedThreshold: 0.01,
},
};
const closeConfig = {
animation: "timing",
config: {
duration: 200,
easing: Easing.linear,
},
};
const Stack = createStackNavigator<RootStackParamList>();
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator
screenOptions={{
gestureDirection: "horizontal",
transitionSpec: {
open: Config,
close: closeConfig,
},
cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
}}
>
<Stack.Screen name="Home" component={Home} />
<Stack.Screen name="Details" component={Details} />
</Stack.Navigator>
</NavigationContainer>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
});
这是因为
timing
和 spring
被推断为字符串而不是字面值。您可以尝试添加as const
:
const closeConfig = {
animation: "timing",
config: {
duration: 200,
easing: Easing.linear,
},
} as const
或者
const closeConfig = {
animation: "timing" as const,
config: {
duration: 200,
easing: Easing.linear,
},
}
或者用类型注释常量:
const closeConfig: TransitionSpec = {
animation: "timing",
config: {
duration: 200,
easing: Easing.linear,
},
}