我正在迁移一个React with TypeScript项目,以使用钩子功能(React v16.7.0-alpha(,但我不知道如何设置被破坏元素的类型。
这里有一个例子:
interface IUser {
name: string;
}
...
const [user, setUser] = useState({name: 'Jon'});
我想强制user
变量的类型为IUser
。我唯一成功的尝试是分两个阶段进行:打字,然后初始化:
let user: IUser;
let setUser: any;
[user, setUser] = useState({name: 'Jon'});
但我相信还有更好的方法。此外,setUser
应该初始化为一个以IUser
为输入的函数,并且不返回任何内容。
此外,值得注意的是,在不进行任何初始化的情况下使用const [user, setUser] = useState({name: 'Jon'});
可以很好地工作,但我希望利用TypeScript强制对init进行类型检查,尤其是在它依赖于某些道具的情况下。
谢谢你的帮助。
使用此
const [user, setUser] = useState<IUser>({name: 'Jon'});
参见确定类型中的对应类型
第一个useState
采用泛型,它将是您的IUser。如果您想要绕过useState
返回的第二个析构函数元素,则需要导入Dispatch。考虑一下您的示例的这个扩展版本,它有一个点击处理程序:
import React, { useState, Dispatch } from 'react';
interface IUser {
name: string;
}
export const yourComponent = (setUser: Dispatch<IUser>) => {
const [user, setUser] = useState<IUser>({name: 'Jon'});
const clickHander = (stateSetter: Dispatch<IUser>) => {
stateSetter({name : 'Jane'});
}
return (
<div>
<button onClick={() => { clickHander(setUser) }}>Change Name</button>
</div>
)
}
看看这个答案。
您还可以在之前声明初始状态,然后可以随时调用它:
type User = typeof initUser;
const initUser = {name: 'Jon'}
...
const [user, setUser] = useState<User>(initUser);
关于I接口前缀:https://basarat.gitbooks.io/typescript/content/docs/styleguide/styleguide.html#interface
https://fettblog.eu/typescript-react/hooks/
// import useState next to FunctionComponent
import React, { FunctionComponent, useState } from 'react';
// our components props accept a number for the initial value
const Counter:FunctionComponent<{ initial?: number }> = ({ initial = 0 }) => {
// since we pass a number here, clicks is going to be a number.
// setClicks is a function that accepts either a number or a function returning
// a number
const [clicks, setClicks] = useState(initial);
return <>
<p>Clicks: {clicks}</p>
<button onClick={() => setClicks(clicks+1)}>+</button>
<button onClick={() => setClicks(clicks-1)}>-</button>
</>
}
class Form {
id: NullNumber = null;
name = '';
startTime: NullString = null;
endTime: NullString = null;
lunchStart: NullString = null;
lunchEnd: NullString = null;
[key: string]: string | NullNumber;
}
export const EditDialog: React.FC = () => {
const [form, setForm] = useState<Form>(new Form());
const inputChange = (e: ChangeEvent<HTMLInputElement>) => {
const element = e.target;
setForm((form: Form) => {
form[element.name] = element.value;
return form;
})
}
return (
<Box pt={3}>
<TextField
required
name="name"
label="Наименование"
defaultValue={form.name}
onChange={inputChange}
fullWidth
/>
</Box>
);
}