You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native+TS项目中使用Pressable的pressed属性出现类型报错如何解决?

报错原因
  1. 你在Props接口中声明isPressed的类型为number,但实际给该属性传值时传入了一个(pressed: boolean) => number类型的函数,类型不匹配触发TS报错。
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 00:15:03