React Native+TS项目中使用Pressable的pressed属性出现类型报错如何解决?
报错原因
- 你在
Props接口中声明isPressed的类型为number,但实际给该属性传值时传入了一个(pressed: boolean) => number类型的函数,类型不匹配触发TS报错。 - Pressable组件仅内置的
style、children等属性支持接收带pressed参数的回调函数,自定义的isPressed属性无法自动获取按压状态,因此你传入的回调函数也不会被执行。
解决方案
推荐使用styled-components直接捕获Pressable的按压状态,无需额外传自定义属性:
const MyBTN = styled.Pressable` background-color: ${globalStyle.primaryColor}; border-radius: 5px; display: flex; align-items: center; padding: 5px; box-shadow: 30px 25px 25px black; // 直接读取Pressable自动注入的pressed状态即可 elevation: ${({ pressed }: { pressed?: boolean }) => pressed ? 10 : 15}; `; const TrainerButton: React.FC<Deck> = ({title, onPress}) => { return ( {/* 不需要手动传isPressed属性 */} <MyBTN onPress={onPress}> <Text> { title } </Text> </MyBTN> ) }
如果你希望把按压状态的逻辑写在组件调用侧,也可以通过Pressable原生支持的style属性实现:
const MyBTN = styled.Pressable` background-color: ${globalStyle.primaryColor}; border-radius: 5px; display: flex; align-items: center; padding: 5px; box-shadow: 30px 25px 25px black; `; const TrainerButton: React.FC<Deck> = ({title, onPress}) => { return ( <MyBTN onPress={onPress} style={({ pressed }) => ({ elevation: pressed ? 10 : 15 })} > <Text> { title } </Text> </MyBTN> ) }
内容的提问来源于stack exchange,提问作者A. Gomes
相关产品推荐
相关产品推荐

