【问题标题】:React native Typescript Touchableopacity props error反应原生 Typescript Touchableopacity 道具错误
【发布时间】:2021-08-27 02:27:45
【问题描述】:

我使用 Styled 组件和 Typescript 创建了一个可重复使用的按钮。我让onPress 无效。我正在使用这个按钮到headStyles。 HeaderStyles 有一个道具名称headerLeftheaderLeft'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 props 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

};

【问题讨论】:

    标签: typescript react-native touchableopacity onpress


    【解决方案1】:

    如果你确定你有来自headerLeftonPress 属性,你可以使用! 来告诉typescript 必须有onPress() 并且它不会是未定义的:

    headerLeft: (props) =>
        props.canGoBack ? <Button onPress={props.onPress!} /> : null, 
    

    更多关于non-null assertion operator - !

    【讨论】:

    • 我可以再问你一个问题吗?
    • 在我的按钮中,我使用的是 react native 的 AccessibilityRole&AccessibilityState。我做了这样的类型:codeshare.io/oQPqdr
    • 您的代码在我这边运行良好。没有类型错误。如果您将鼠标悬停在hint 上,是string | undefined 吗?也许你可以试试Platform.select&lt;string | undefined&gt;({ ios: hint });
    • 非常感谢。你真是打字高手?
    • 当我将它用于我的按钮时,它也会引发 Typescript 错误:Overload 1 of 2, '(props: Omit, never> & Partial, never>>, "theme"> & { ...; } & { ...; } & { ...; }): ReactElement<...>',给出以下错误.类型'{孩子:元素;可访问性标签:字符串 |不明确的;可访问性提示:字符串 |不明确的;可访问性角色:可访问性角色 |不明确的;可访问性状态:可访问性状态 |不明确的;测试ID:字符串|
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    相关资源
    最近更新 更多