React Typescript - 传递道具到Hooks之间的类型错误

问题描述 投票:0回答:1

我已经创建了 这个codeandbox复制了我的问题

  • 1)我首先创建了 <Input> 组件,(用于样式设计和跟踪输入是否有内容。
  • 2) 一切都能正常工作,但是由于需要在项目中添加更多的表单,我想,也许我可以创建一个useInput钩子来管理值的更新,而不是必须在项目中添加 onChange: {e => {setSomething(e.target.value)}} 所有的时间。

所以我创建了这些useInput,但我得到了这个恼人的红色linter错误。它可能是一些基本的类型问题,但我可以弄清楚。如何摆脱这个问题。any 型解决方案? 先谢谢你

错误的截图和下面的代码块,但 沙盘测试

enter image description here

# useInput.tsx

import { useState, ChangeEvent } from "react";

export type onChangeType = (event: ChangeEvent<HTMLInputElement>) => void;
const useInput = (initialValue = "") => {
  const [value, setValue] = useState(initialValue);

  const reset = () => setValue("");

  const onChange: onChangeType = e => {
    setValue(e.target.value);
  };

  return [value, onChange, reset];
};

export default useInput;

# Input.tsx

import React, { useState, ChangeEvent } from "react";
import styled, { css } from "styled-components";

import onChangeType from "./hooks/useInput";

interface iLabelProps {
  hasContent: boolean;
}

const hasContentCSS = () => css`
  border: 5px solid royalblue;
`;

const Label = styled.label<iLabelProps>```

interface iInput {
  readonly type?: string;
  readonly name: string;
  readonly label: string;
  value?: string | number | string[] | null;
  defaultValue?: string | number | string[] | null;
  readonly onChange?: (event: ChangeEvent<HTMLInputElement>) => void;
}

export const Input = ({
  name = "email",
  label,
  value = null,
  defaultValue = null,
  onChange = null
}: iInput) => {
  const [hasContent, setHasContent] = useState(!!defaultValue);

  const onBlur = value => {
    setHasContent(value.length > 0);
  };

  return (
    <Label hasContent={hasContent}>
      <input
        type="text"
        name={name}
        {...defaultValue && { defaultValue: defaultValue }}
        {...!defaultValue && { value: value ? value : "" }}
        {...onChange && { onChange: onChange }}
        onBlur={e => onBlur(e.target.value)}
      />
      <span>{label}</span>
    </Label>
  );
};

reactjs typescript react-hooks typescript-typings react-props
1个回答
1
投票

问题来自于从useInput钩子中返回值的错误推断类型。TS认为类型是 (string | onChangeType)[]. 这意味着 stringonChangeType 可以在数组中的任何位置,而你有非常固定的顺序。

为了解决这个问题,你必须稍微帮助它,要么像这样把你返回的数组投掷出去。

return [value, onChange, reset] as [string, onChangeType, () => void];

或明确指定useInput函数的返回类型。

const useInput = (initialValue = ""): [string, onChangeType, () => void] => {...}
© www.soinside.com 2019 - 2024. All rights reserved.