javascript - React Native with Typescript - 可按下的按下属性
问题描述
我是在 React 中使用 typescript 的新手,我不能在使用 typescript的 react 本机应用程序中使用pressed
prop 。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)
解决方案
您应该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>
);
}
推荐阅读
- javascript - 在 ReactJS 中使用 Jquery 方法 getBoundingClientRect 得到错误
- python-3.x - 特殊字符解码打印问题
- python - 将字典解压到单个 DataFrame 中
- php - 如何使用 MAMP 5.1 启用通用 PHP 日志和 apache 请求日志
- python-3.x - 如何检查用户名是否存在于 cgi 脚本中的数据库中?
- html - 尝试在 Mac 上使用 Unix 从 HTML 文档中的一行中提取版本号
- sql-server - 如何为生产数据库生成脚本?
- python - 提高图像处理的准确性以计数真菌孢子
- javascript - 过滤角度json 7
- android - 如何在osmdroid中将指南针调整为地图