我正在迁移一个带有TypeScript的React项目,以使用钩子功能(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上的类型检查,特别是如果它依赖于一些道具。
谢谢你的帮助。
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>
</>
}
首先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>
)
}
请看这个答案。
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>
</>
}