React TS:将函数作为 props 传递时不要重复类型,请使用它们的类型。

2025-05-25

React TS:将函数作为 props 传递时不要重复类型,请使用它们的类型。

当你将函数作为 props 传递时,不要重复类型,而是使用它们的类型。

假设有一个名为“SignUpForm”的组件。



export interface SignUpFormProps {
  onSubmit?: (values: {
    username: string;
    nickname: string;
    password: string;
  }) => void;
}

export const SignUpForm = ({ onSubmit }: SignUpFormProps) => {
  const [values, setValues] = useState({
    username: "",
    nickname: "",
    password: "",
  });

  const handleChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
    setValues((prevValues) => ({
      ...prevValues,
      [e.target.name]: e.target.value,
    }));
  };

  const handleSubmit: React.FormEventHandler = (e) => {
    e.preventDefault();
    onSubmit?.(values);
  };

  return (
    <form
      onSubmit={handleSubmit}
      style={{ display: "flex", flexDirection: "column" }}
    >
      <input
        type="text"
        name="username"
        value={values.username}
        onChange={handleChange}
      />
      <input
        type="text"
        name="nickname"
        value={values.nickname}
        onChange={handleChange}
      />
      <input
        type="password"
        name="password"
        value={values.password}
        onChange={handleChange}
      />
      <button type="submit">Submit</button>
    </form>
  );
};


Enter fullscreen mode Exit fullscreen mode

onSubmit如果存在,提交事件会将参数“用户名”、“昵称”和“密码”传递给prop。

您可以像下面这样传递函数。



function App() {
  const handleSubmit = (
    values
  ) => {
    console.log(values);
  };

  return (
    <div>
      <SignUpForm onSubmit={handleSubmit} />
    </div>
  );
}


Enter fullscreen mode Exit fullscreen mode

如果您没有选项"noImplicitAny": false,就会发生错误。

任何类型错误

为了避免这个问题,你可以重复的类型onSubmit

重复类型

如果只是这样重复的话,就必须根据道具不断更新onSubmit

这会让你感到困扰。
在这种情况下,你可以使用括号来获取接口的字段类型。

字段类型




function App() {
  const handleSubmit:SignUpFormProps['onSubmit'] = (
    values
  ) => {
    console.log(values);
  };

  return (
    <div>
      <SignUpForm onSubmit={handleSubmit} />
    </div>
  );
}


Enter fullscreen mode Exit fullscreen mode

如果没有接口,则使用React.ComponentProps

使用 React 组件 props 获取字段类型



function App() {
  const handleSubmit: React.ComponentProps<typeof SignUpForm>["onSubmit"] = (
    values
  ) => {
    console.log(values);
  };

  return (
    <div>
      <SignUpForm onSubmit={handleSubmit} />
    </div>
  );
}


Enter fullscreen mode Exit fullscreen mode

就是这样。希望对大家有帮助。

祝您编码愉快!


+
感谢大家阅读。不过我不确定这个例子是否合适。重点是你可以获取字段类型,并且可以在其他包中使用它。再次感谢你们的关注,写得真好!

文章来源:https://dev.to/lico/react-ts-dont-repeat-the-type-when-you-pass-functions-as-props-use-their-types-5h6h
PREV
学习热爱软件开发书籍💙
NEXT
7分钟用JavaScript创建神经网络!简单理论 正向传播 反向传播(或反向传播,简称backprop) 实践 结论