【问题标题】:How do I add type to onChange & onClick functions in typescript react如何在打字稿反应中向 onChange 和 onClick 函数添加类型
【发布时间】:2021-11-27 06:24:02
【问题描述】:

我已经定义了一个组件

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}
      }
    />
);

我首先将我的反应组件转换为打字稿,我有点困惑我应该为我正在检索它的道具编写什么类型的函数,在类型道具启动之上,我得到那个字符串和布尔值,但是有人应该怎么做处理事件函数类型

【问题讨论】:

    标签: javascript reactjs typescript material-ui


    【解决方案1】:

    您可以将handleClick 定义为React.MouseEventHandler&lt;HTMLInputElement&gt;

    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" />;
    }
    

    【讨论】:

      【解决方案2】:

      由于我们希望使用 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}
          />
      );
      

      【讨论】:

        猜你喜欢
        • 2019-04-23
        • 2021-12-24
        • 2021-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-26
        • 1970-01-01
        相关资源
        最近更新 更多