在使用 TypeScript 进行 React 时,输入字段在“值”处给出错误

问题描述 投票:0回答:2
import { SetStateAction, useState } from "react"

const Loginform =() =>{
    const [name, setName] = useState<String | null>();
    const [fullname, setFullname] = useState<String | null>();
    const inputEvent =(event: { target: { value: SetStateAction< String |null | undefined  >; }; })=>{
       
        setName(event.target.value)
    }
    const Submit = ()=>{
        setFullname(name)
    }
    return <>
    <h1>Enter Your Name </h1>
    <input type="text" placeholder="Enter your name" onChange={inputEvent} value={name}/>
    <button onClick={Submit}>Submit</button>
    <h1>Hi {fullname==null? "Guest" :fullname}</h1>
    </>
}
export default Loginform
<input type="text" placeholder="Enter your name" onChange={inputEvent} value={name}/>

上一行中的“value”属性显示错误

这是错误详细信息:

(property) React.InputHTMLAttributes<HTMLInputElement>.value?: string | number | readonly string[] | undefined
Type 'String | null | undefined' is not assignable to type 'string | number | readonly string[] | undefined'.
  Type 'null' is not assignable to type 'string | number | readonly string[] | undefined'.ts(2322)
index.d.ts(2398, 9): The expected type comes from property 'value' which is declared here on type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>'

也尝试写 return

as any
。或者尝试添加
string[]
,但出现错误。

reactjs typescript
2个回答
1
投票

进行以下调整:

  • String
    替换为
    string
    ,因为原始 Typescript 类型是小写的 (
    number, string, boolean, etc
    )
  • TypeScript 报告此错误,因为属性值不接受
    null
    作为值,而是接受
    undefined
    。将代码更新为:
const [name, setName] = useState<string>()

这会使用

string
作为默认类型来初始化状态。 初始状态隐式地被视为
undefined
,因为如果未显式提供,TypeScript 会将类型的默认值设置为
undefined

  • 为了简单起见,您不需要解构事件。使用内联函数,如下例所示:
    <input type="text" placeholder="Enter your name" onChange={(e) => setName(e.target.value)} value={name}/>

0
投票

我使用你的代码创建了一个 CodeSanbox,它似乎只需要很少的修改就可以正常工作。

您可以在这里找到沙盒

这是我想出的代码

import { SetStateAction, useState } from "react";

const Loginform = () => {
  const [name, setName] = useState<string | null>();
  const [fullname, setFullname] = useState<string | null>();
  const inputEvent = (event: {
    target: { value: SetStateAction<string | null | undefined> };
  }) => {
    setName(event.target.value);
  };
  const Submit = () => {
    setFullname(name);
  };
  return (
    <div>
      <h1>Enter Your Name </h1>
      <input
        type="text"
        placeholder="Enter your name"
        onChange={inputEvent}
        value={name}
      />
      <button onClick={Submit}>Submit</button>
      <h1>Hi {fullname == null ? "Guest" : fullname}</h1>
    </div>
  );
};
export default Loginform;
© www.soinside.com 2019 - 2024. All rights reserved.