如何解决反应原生 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
道具无效?
这是我可重复使用的 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;
这是headerStyles
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
属性中的 headerLeft
,你可以使用 !
来通知 typescript 必须有 onPress()
并且它不会是未定义的:
headerLeft: (props) =>
props.canGoBack ? <Button onPress={props.onPress!} /> : null,
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。