React Native with Typescript - Pressable pressed property



我是React中使用typescript的新手,我不能在使用typescript的React原生应用程序中使用Pressablepressedprop。

我正在使用样式组件和定义一个道具来改变样式时,Pressable被按下:

interface Props {
isPressed: number;
}
const MyBTN = styled.Pressable<Props>`
background-color: blue;
border-radius: 5px;
display: flex;
align-items: center;
padding: 5px;
background-color: ${globalStyle.primaryColor};
box-shadow: 30px 25px 25px black;
elevation: ${(props) => props.isPressed};
`;
const TrainerButton: React.FC<Deck> = ({title, onPress}) => {
return (
<MyBTN onPress={onPress} isPressed={({ pressed } : any) => pressed ? 10 : 15}>
<Text>
{ title }
</Text>
</MyBTN>
)
}

我得到一个错误在按下的道具isPressed={({ pressed } : any) => pressed ? 10 : 15}:

No overload matches this call.
Overload 1 of 2, '(props: Omit<Omit<PressableProps & RefAttributes<View> & Props, never> & Partial<Pick<PressableProps & RefAttributes<View> & Props, never>>, "theme"> & { ...; } & { ...; }): ReactElement<...>', gave the following error.
Type '({ pressed }: any) => 10 | 15' is not assignable to type 'number'.
Overload 2 of 2, '(props: StyledComponentPropsWithAs<ForwardRefExoticComponent<PressableProps & RefAttributes<View>>, DefaultTheme, Props, never, ForwardRefExoticComponent<...>, ForwardRefExoticComponent<...>>): ReactElement<...>', gave the following error.
Type '({ pressed }: any) => 10 | 15' is not assignable to type 'number'.ts(2769)

您应该在接口Props中定义MyBTN的Props。isPressed的类型是number,但您正在尝试传递回调。

更确切地说,根据按钮是否被按下传递一个布尔值给你的样式化组件,然后使用它来显示适当的高度。你还需要从某处获得isPressed布尔值,在受压的情况下,我们可以使用onPressIn和onPressOut回调:

interface Props {
isPressed: boolean;
}
const MyBTN = styled.Pressable<Props>`
background-color: blue;
border-radius: 5px;
display: flex;
align-items: center;
padding: 5px;
background-color: ${globalStyle.primaryColor};
box-shadow: 30px 25px 25px black;
elevation: ${(props) => props.isPressed ? 10 : 15};
`;
const TrainerButton: React.FC<Deck> = ({title, onPress}) => {
const [isPressed, setIsPressed] = useState<boolean>(false);
const onPressIn = () => setIsPressed(true);
const onPressOut = () => setIsPressed(false);
return (
<MyBTN onPress={onPress} isPressed={isPressed} onPressIn={onPressIn} onPressOut={onPressOut}>
<Text>
{ title }
</Text>
</MyBTN>
);
}

最新更新