类型“(text: string) => void”不可分配给类型“() => void”

ara*_*nah 3 typescript react-native

我正在为 TextInput 创建一个自定义组件。但是当我尝试将函数道具传递给自定义组件时遇到问题。这是代码

// Screen.tsx
export const RegisterScreen = ({props}: Props) => {
  const [text, setText] = useState("");
 
  const onChangeInputText = (text: string) => setText(text);

  return (
    <View>
        <CustomInput onChangeText={onChangeInputText} text={text} />
    </View>

// CustomTextInput.tsx
type Props = {
  onChangeText: () => void;
  text?: string;
};

export const CustomInput = ({ onChangeText, text }: Props) => {
  return (
    <TextInput
      style={styles.container}
      onChangeText={onChangeText}
      value={text}
      placeholder="Type here"
    />
  );
};
Run Code Online (Sandbox Code Playgroud)

使用这段代码,我得到了这个错误

Type '(text: string) => void' is not assignable to type '() => void'
Run Code Online (Sandbox Code Playgroud)

我想我知道是什么原因导致这个问题(可能是在类型声明上?),但由于这实际上是我第一次尝试 TypeScript,所以我真的不知道如何解决这个问题。首先尝试用谷歌搜索这个问题,但我没有发现任何与我的类似的错误。

Nic*_*wer 8

该函数的类型定义表示“嘿,我需要传递一个字符串才能完成我的工作”:

const onChangeInputText = (text: string) => setText(text);
Run Code Online (Sandbox Code Playgroud)

但 onChangeText 属性的定义是“我不会向你传递任何内容”:

type Props = {
  onChangeText: () => void;
  text?: string;
};
Run Code Online (Sandbox Code Playgroud)

您的代码实际上会传递一个字符串,因此您只需要更新道具上的类型即可。

type Props = {
  onChangeText: (val: string) => void;
  text?: string;
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!不敢相信我无法弄清楚这一点! (2认同)