React Native TextInput onChange 事件类型与 onChange 属性不匹配

问题描述 投票:0回答:1

我正在尝试使用 React Native TextInput 组件创建一个自定义组件,并将 onChange 属性与其他一些代码一起传递给 TextInput,但是根据打字稿,

event
类型是错误的。

自定义组件:

import type { TextInputProps } from "react-native";

interface InputProps extends InputHTMLAttributes<TextInputProps> {
  errorMsg?: string;
  labelText?: string;
  appearance?: "primary" | "rounded";
}

export default function Input(props: HTMLInputElement, InputProps) {
  return
  <TextInput
    placeholder=(props.placeholder)
    onChange={(e) => {
      setText(e.nativeEvent.text)

      if(props.onChange) props.onChange(e)
    }}
  />
}

但是打字稿说:

Argument of type 'NativeSyntheticEvent<TextInputChangeEventData>' is not assignable to parameter of type 'ChangeEvent<TextInputProps>'.
  Types of property 'target' are incompatible.
    Type 'Component<unknown, {}, any> & Readonly<NativeMethods>' is not assignable to type 'EventTarget & TextInputProps'.
      Type 'Component<unknown, {}, any> & Readonly<NativeMethods>' is missing the following properties from type 'EventTarget': addEventListener, dispatchEvent, removeEventListenerts(2345)
(parameter) e: NativeSyntheticEvent<TextInputChangeEventData>

尝试更改类型并在网上查找类似问题但没有成功

typescript react-native
1个回答
0
投票

我觉得这就是您正在寻找的。由于 TextInput 已经是一个组件,您只需扩展它的 props 即可。

interface InputProps extends TextInputProps {
  errorMsg?: string;
  labelText?: string;
  appearance?: "primary" | "rounded";
}

export default function Input(props: InputProps) {
  return  <TextInput placeholder={props.placeholder}
    onChange={(e) => {

      if(props.onChange) props.onChange(e)
    }}
  />
}

© www.soinside.com 2019 - 2024. All rights reserved.