简体   繁体   English

如何在 typescript 中的 onChange 和 onClick 函数中添加类型

[英]How do I add type to onChange & onClick functions in typescript react

I have defined a component我已经定义了一个组件

type Props = {
  label:string,
  autoFocus:boolean,
  onClick:(e: React.ClickEvent<HTMLInputElement>) => void,
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void
}

const Input = ({ handleChange, label, autoFocus, handleClick  }:Props) => (
    <TextField
      onChange={handleChange}
      required
      label={label}
      autoFocus={autoFocus}
      onClick={handleClick}
      }
    />
);

I am converting my react components into typescript for the first, I am a bit confused about what type should I write for functions that I am retrieving it props, Above type Props initiation, I get that string & boolean but how someone should handle event function typing我首先将我的反应组件转换为 typescript,我有点困惑我应该为我正在检索它的道具编写什么类型的函数,在类型道具启动之上,我得到了那个字符串和 boolean 但有人应该如何处理事件 ZC1C125268E68A455打字

You can define handleClick as React.MouseEventHandler<HTMLInputElement> :您可以将handleClick定义为React.MouseEventHandler<HTMLInputElement>

import { TextField } from "@material-ui/core";
import React from "react";

type Props = {
  label: string;
  autoFocus?: boolean;
  handleClick?: React.MouseEventHandler<HTMLInputElement>;
  handleChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
};

const Input = ({ handleChange, label, autoFocus, handleClick }: Props) => (
  <TextField
    onChange={handleChange}
    required
    label={label}
    autoFocus={autoFocus}
    onClick={handleClick}
  />
);

export default function App() {
  return <Input label="CustomInput" />;
}

编辑希望-estrela-4jhlo

As we want to use MUI to support the types and to be a single source of truth, I'd suggest inferring the types from material UI itself, instead of creating separate types.由于我们希望使用 MUI 来支持类型并成为单一事实来源,我建议从材质 UI 本身推断类型,而不是创建单独的类型。

import { TextField, TextFieldProps } from '@mui/material';

type Props = {
    handleChange: TextFieldProps['onChange'];
    handleClick: TextFieldProps['onClick'];
    label: TextFieldProps['label'];
    autoFocus: TextFieldProps['autoFocus'];
};

const Input = ({ handleChange, label, autoFocus, handleClick }: Props) => (
    <TextField
        onChange={handleChange}
        required
        label={label}
        autoFocus={autoFocus}
        onClick={handleClick}
    />
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM