【问题标题】:React Custom Hook with Typescript Type error "Property 'x' does not exist on type 'interface | (({ target }: any) => void)'.ts(2339)"React Custom Hook with Typescript Type error "Property 'x' does not exist on type 'interface | (({ target }: any) => void)'.ts(2339)"
【发布时间】:2020-10-18 10:45:06
【问题描述】:

我正在尝试使用自定义钩子管理表单,所以我有这个代码

FormHook.tsx:

import { useState } from 'react';

interface ICampos  {
    name: string;
    email: string;
    password: string;
}


const useForm = (initialState: ICampos) => {
    
    const [values, setValues] = useState(initialState);


    const handleInputChange = ({ target }: any) => {
        setValues({
            ...values,
            [target.name]: target.value
        })
    };

    return [values, handleInputChange];
}

export default useForm

FormWithCustomHook.tsx:

import React from 'react'
import './effects.css' 
import useForm from '../../hooks/useForm';

interface ICampos  {
    name: string;
    email: string;
    password: string;
}

const FormWithCustomHook = () => {

    const [formValues, handleInputChange] = useForm({
        name: '',
        email: '',
        password: ''
    });

    const { name, email, password } = formValues;



    return (
        <>
            <h1> FormWithCustomHook </h1>
            <hr />

            <div className="form-group">
                <input
                    type="text"
                    name="name"
                    className="form-control"
                    placeholder="Tu nombre"
                    autoComplete="off"
                    value={name}
                    onChange={handleInputChange} />
            </div>
            
            <div className="form-group">

                <input
                    type="email"
                    name="email"
                    className="form-control"
                    placeholder="email@ejemplo.com"
                    autoComplete="off"
                    value={email}
                    onChange={handleInputChange} />
            </div>

            <div className="form-group">

                <input
                    type="password"
                    name="password"
                    className="form-control"
                    placeholder="*****"
                    autoComplete="off"
                    value={password}
                    onChange={handleInputChange} />
            </div>

        </>
    )
}

export default FormWithCustomHook;

我在 FormWithCustomHook.tsx 行遇到了这个错误:

const { name, email, password } = formValues;

它只在电子邮件和密码上标记错误:

“ICampos | 类型”上不存在“属性“电子邮件” (({ target }: any) => void)'.ts(2339)'

在我的 onChange 里面的输入说:

键入'ICampos | (({ target }: any) => void)' 不能分配给类型 '((event: ChangeEvent) => void) |不明确的'。 类型“ICampos”不可分配给类型“(事件:ChangeEvent)=> void”。 类型“ICampos”不匹配签名“(事件:ChangeEvent):void”.ts(2322) index.d.ts(2092, 9):预期类型来自属性“onChange”,该属性在此处声明为类型“DetailedHTMLProps”

我尝试在 customhook.tsx 上添加类型,但我真的不明白这个错误

【问题讨论】:

  • 我已经更新了我的答案,显示了一个输入数组的解决方案。

标签: reactjs typescript react-hooks


【解决方案1】:

钩子不知道数组的顺序。所以它可能是ICampos | Handler 或Handler | ICampos。您有两种选择:

你可以在钩子上键入返回数组:

const useForm = (
  initialState: ICampos
): [ICampos, ({ target }: any) => void] => {
  const [values, setValues] = useState<ICampos>(initialState);

  const handleInputChange = ({ target }: any) => {
    setValues({
      ...values,
      [target.name]: target.value
    });
  };

  return [values, handleInputChange];
};

或者你可以返回一个对象而不是一个数组。我更喜欢这个,因为我不喜欢输入数组。

import { useState } from "react";

interface ICampos {
  name: string;
  email: string;
  password: string;
}

const useForm = (initialState: ICampos) => {
  const [values, setValues] = useState<ICampos>(initialState);

  const handleInputChange = ({ target }: any) => {
    setValues({
      ...values,
      [target.name]: target.value
    });
  };

  return { values, handleInputChange };
};

export default useForm;
import React from "react";
import "./effects.css";
import useForm from "./useForm";

interface ICampos {
  name: string;
  email: string;
  password: string;
}

const FormWithCustomHook = () => {
  const { values, handleInputChange } = useForm({
    name: "",
    email: "",
    password: ""
  });

  const { name, email, password } = values;

  return (
    <>
      <h1> FormWithCustomHook </h1>
      <hr />

      <div className="form-group">
        <input
          type="text"
          name="name"
          className="form-control"
          placeholder="Tu nombre"
          autoComplete="off"
          value={name}
          onChange={handleInputChange}
        />
      </div>

      <div className="form-group">
        <input
          type="email"
          name="email"
          className="form-control"
          placeholder="email@ejemplo.com"
          autoComplete="off"
          value={email}
          onChange={handleInputChange}
        />
      </div>

      <div className="form-group">
        <input
          type="password"
          name="password"
          className="form-control"
          placeholder="*****"
          autoComplete="off"
          value={password}
          onChange={handleInputChange}
        />
      </div>
    </>
  );
};

export default FormWithCustomHook;

【讨论】:

  • 是的,这是我的第一种方法,但是如果你返回一个对象,它会让你在导出时使用对象变量的名称,如果你返回一个数组,你可以重命名函数和在组件中添加您喜欢的对象,这使它们更加模块化:(
  • 在解构对象时,您始终可以使用别名。如果要使用数组,则需要输入,如上图
  • 向上,谢谢!这正是我要找的,抱歉,没有看到您的编辑。
猜你喜欢
  • 2019-03-11
  • 2019-05-05
  • 2019-06-12
  • 2022-11-17
  • 2022-12-16
  • 2022-12-27
  • 2022-11-09
  • 1970-01-01
  • 2022-07-14
相关资源
最近更新 更多