React Native 将 onPress 调用的接口声明为 void 打字稿错误

Bet*_*IGM 2 javascript typescript reactjs react-native

我正在尝试从 TouchableOpacity 组件内的 onPress 调用中消除此打字稿错误。

Called when the touch is released, but not if cancelled (e.g. by a scroll that steals the responder lock).

No overload matches this call.
  Overload 1 of 2, '(props: (TouchableOpacityProps & GenericTouchableProps) | Readonly<TouchableOpacityProps & GenericTouchableProps>): TouchableOpacity', gave the following error.
    Type 'void' is not assignable to type '(((event: GestureResponderEvent) => void) & (() => void)) | undefined'.
  Overload 2 of 2, '(props: TouchableOpacityProps & GenericTouchableProps, context: any): TouchableOpacity', gave the following error.
    Type 'void' is not assignable to type '(((event: GestureResponderEvent) => void) & (() => void)) | undefined'.ts(2769)
index.d.ts(5265, 5): The expected type comes from property 'onPress' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<TouchableOpacity> & Pick<Readonly<TouchableOpacityProps & GenericTouchableProps> & Readonly<...>, "hitSlop" | ... 36 more ... | "containerStyle"> & Partial<...> & Partial<...>'
index.d.ts(5265, 5): The expected type comes from property 'onPress' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<TouchableOpacity> & Pick<Readonly<TouchableOpacityProps & GenericTouchableProps> & Readonly<...>, "hitSlop" | ... 36 more ... | "containerStyle"> & Partial<...> & Partial<...>'

Run Code Online (Sandbox Code Playgroud)

正如您在下面的代码中看到的,此错误出现在我的 TouchableOpacity 按钮的 onPress 调用上。

  const handleChange = (id: Number) => {
    switch (id) {
      case 0:
        console.log('Se preciono el primer boton');
        break;
      default:
        console.log('default');
    }
  };

  return (
    <View style={styles.tabsContainer}>
      <TouchableOpacity style={styles.tab} onPress={handleChange(0)}>
        <Text style={styles.text}>TITULO DE PRUEBA</Text>
      </TouchableOpacity>
    </View>
  );
};

Run Code Online (Sandbox Code Playgroud)

我想我只需要将此 onPress 调用声明为 void 函数,但我不知道如何......有人有任何建议吗?

类型错误

Mic*_*ung 6

尝试用包装函数包装调用函数() =>,以避免在 onPress 之前执行函数并键入错误。

onPress={() => handleChange(0)}
Run Code Online (Sandbox Code Playgroud)