React Native(Expo) + TypeScript中android_ripple类型错误如何解决
解决React Native(Expo)中Pressable组件android_ripple的TypeScript类型错误
错误原因
你写的android_ripple={{ color: { rippleColor }, borderless: true }}里,color字段被错误地包裹在了一个对象中。React Native要求color的值必须是ColorValue类型(比如十六进制字符串、rgb()值、颜色名称等),而不是嵌套对象,这直接导致了类型不匹配的报错。
修复步骤
- 修正color的赋值方式:直接传入
rippleColor变量,不要额外用对象包裹 - 给组件Props添加类型定义:明确
rippleColor的类型为ColorValue,避免TypeScript将其推断为any
修复后的完整代码
import { Pressable, Text, View, ColorValue, PressableProps } from "react-native"; // 定义组件Props的类型 type ButtonProps = { rippleColor?: ColorValue; disabled?: boolean; onPress?: PressableProps['onPress']; text: string; }; const Button = ({ rippleColor, disabled = false, onPress, text, }: ButtonProps) => { return ( <View> <Pressable disabled={disabled} android_ripple={{ color: rippleColor, borderless: true }} onPress={onPress} > <Text>{text}</Text> </Pressable> </View> ); };
额外说明
- 如果需要给
rippleColor设置默认值,可以在Props类型里直接指定,比如rippleColor: ColorValue = '#e0e0e0' ColorValue是React Native内置的类型,涵盖了所有合法的颜色格式,能完美匹配android_ripple的color字段要求
内容的提问来源于stack exchange,提问作者louis
相关产品推荐
相关产品推荐

