首页 > 解决方案 > React Native with Typescript - 可按下的按下属性

问题描述

我是在 React 中使用 typescript 的新手,我不能在使用 typescript的 react 本机应用程序中使用pressedprop 。Pressable

我正在使用样式化组件并定义一个道具以在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)

标签: javascriptreactjstypescriptreact-native

解决方案


您应该MyBTN在界面中定义 Props Props。的类型isPressed是数字,但您正尝试传入回调。

相反,根据按钮是否被按下,将布尔值传递给您的样式组件,然后使用它来显示适当的高度。您还需要从某个地方获取 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>
   );
}


推荐阅读