typescript - 反应原生 Typescript Touchableopacity 道具错误
问题描述
我使用 Styled 组件和 Typescript 创建了一个可重复使用的按钮。我 onPress
作废了。我正在使用这个按钮到headStyles。HeaderStyles 有一个道具名称headerLeft
。 headerLeft's
props 的 onPress 是可选的或未定义的。当我将此道具传递给我的 Button 时,我得到了预期的 Typescript 错误。这是错误:Type '(() => void) | undefined' is not assignable to type '() => void'. Type 'undefined' is not assignable to type '() => void'.ts(2322)
。有什么办法让我的headerLeft
道具 onPress 无效?
这是我的可重复使用的 Button 组件:
import React from 'react';
import styled from 'styled-components/native';
type Props = {
onPress: () => void;
};
const BackButtonContainer = styled.TouchableOpacity`
padding-vertical: 16px;
padding-horizontal: 24px;
`;
const Button = ({ onPress }: Props) => {
return (
<BackButtonContainer
onPress={onPress}>
</BackButtonContainer>
);
};
export default Button;
这是标题样式
import { StackNavigationOptions } from '@react-navigation/stack';
import React from 'react';
import Button from './buttons;
export const headerStyles: StackNavigationOptions = {
headerStyle: {
elevation: 0,
borderBottomWidth: 0,
shadowOffset: { height: 0, width: 0 },
},
headerTitleAlign: 'center',
headerTintColor: colors.greyGradient[800],
headerLeft: (props) =>
props.canGoBack ? <Button onPress={props.onPress} /> : null, //In here I am getting typescript error
};
解决方案
如果你确定你有onPress
fromheaderLeft
道具,你可以使用!
来告知 typescript 必须有onPress()
并且它不会是未定义的:
headerLeft: (props) =>
props.canGoBack ? <Button onPress={props.onPress!} /> : null,
更多关于非空断言运算符 -!
推荐阅读
- wix - 有什么方法可以抑制控制面板中 WiX 引导程序设置显示的默认大小
- python - 来自特定端口的 Python TCP 客户端
- php - 我在 wordpress 上上传了一个自定义主题,但它的样式不起作用我无法将样式排入队列
- ruby - 如何在 Ruby 中表达这种数据类型?
- json - 有条件地确定字段的必要性
- angular - Apollo Angular Add--无法读取 tsconfig.base.json
- github - GitHub PR UI 中的选项卡大小不一致
- phpmyadmin - 无法打开 XAMPP PHP Admin,出现致命错误:未捕获错误:找不到类“PhpMyAdmin\Template”
- swift - 使滑块值只能以一种方式调整
- unity3d - unity LookAt 而不是 Forward