当前位置:网站首页>Master the pose of hook in typescript in 3 minutes
Master the pose of hook in typescript in 3 minutes
2022-07-22 03:16:00 【flytam】
hook
combination typescript It's very fragrant . This paper mainly introduceshook
combination typescript How to use , enjoy ts Editor tips and type constraints
useState
useState
If the initial value is not null/undefined
Words , It has the ability of type derivation , Infer the type... From the initial value passed in ; The initial value is null/undefined
You need to pass the type definition to constrain . In general , We recommend the incoming type ( adopt useState The first generic parameter of ).
// here ts It can be inferred value And can be used for setValue Function call to constrain
const [value, setValue] = useState(0);
interface MyObject {
foo: string;
bar?: number;
}
// It needs to be delivered here MyObject To restrain value, setValue
// Generally, the incoming type is recommended
const [value, setValue] = useState<MyObject>(null);
useContext
useContext
Generally according to the incoming Context We can infer the return value of . There is no need to show the delivery type
type Theme = 'light' | 'dark';
// We are createContext Just passed on the type
const ThemeContext = createContext<Theme>('dark');
const App = () => (
<ThemeContext.Provider value="dark">
<MyComponent />
</ThemeContext.Provider>
)
const MyComponent = () => {
// useContext according to ThemeContext Infer the type , There is no need to show the transmission
const theme = useContext(ThemeContext);
return <div>The theme is {theme}</div>;
useEffect
useLayoutEffect
no return value , No need to pass type
useCallback
useMemo
useMemo
No need to pass type , The type can be inferred from the return value of the function
useCallback
No need to pass type , The type can be inferred from the return value of the function . But notice that the function's arguments need to define the type , Otherwise, it is inferred that any 了 !
const value = 10;
// Deduce result yes number type
const result = useMemo(() => value * 2, [value]);
const multiplier = 2;
// Deduce (value: number) => number
// Notice the function arguments value Need to define type
const multiply = useCallback((value: number) => value * multiplier, [multiplier]);
useRef
useRef
You can infer the type when you pass a non null initial value , You can also define a type by passing in the first generic parameter , constraint ref.current
The type of .
const MyInput = () => {
// Constraint here inputRef It's a html Elements
const inputRef = useRef<HTMLInputElement>(null);
return <input ref={inputRef} />
}
// Automatically infer myNumberRef.current yes number type
const myNumberRef = useRef(0);
myNumberRef.current += 1;
useReducer
Just for the incoming useReducer
Of reducer The input parameters of the function state
and action
With type constraints, you can infer
interface State {
value: number;
}
type Action =
| { type: 'increment' }
| { type: 'decrement' }
| { type: 'incrementAmount'; amount: number };
const counterReducer = (state: State, action: Action) => {
switch (action.type) {
case 'increment':
return { value: state.value + 1 };
case 'decrement':
return { value: state.value - 1 };
case 'incrementAmount':
return { value: state.value + action.amount };
default:
throw new Error();
}
};
// It can be inferred here state by State type
const [state, dispatch] = useReducer(counterReducer, { value: 0 });
// Be able to restrict incoming dispatch Parameters of , accord with Action type
dispatch({ type: 'increment' });
dispatch({ type: 'decrement' });
dispatch({ type: 'incrementAmount', amount: 10 });
// TypeScript compilation error
dispatch({ type: 'invalidActionType' });
useImperativeHandle
useImperativeHandle
Generally, it is less used , It is generally used to select function components for external exposure ref Property is called , Need to cooperate with forwardRef
Use .
The following example . You need to define exposed interfaces MyInputHandles
, Function components use React.RefForwardingComponent
Exposed interface calls as generic parameters . And then it's bound
// MyInputHandles Needs to be given to the parent component useRef Use as type and RefForwardingComponent Pass in constraints as generic parameters
export interface MyInputHandles {
focus(): void;
}
// Use RefForwardingComponent Type to define components , The first generic parameter is exposed handle, The second is Props
const MyInput: RefForwardingComponent<MyInputHandles, MyInputProps> = (
props,
ref
) => {
const inputRef = useRef<HTMLInputElement>(null);
useImperativeHandle(ref, () => ({
// The return here will be used automatically MyInputHandles Type constraints
focus: () => {
if (inputRef.current) {
inputRef.current.focus();
}
},
}));
return <input {...props} ref={inputRef} />;
};
// Function components must use forwardRef So that external components can use the ref
export default forwardRef(MyInput);
// Parent component
const Autofocus = () => {
// Be able to restrain myInputRef.current The type of
const myInputRef = useRef<MyInputHandles>(null);
useEffect(() => {
if (myInputRef.current) {
myInputRef.current.focus();
}
});
return <MyInput ref={myInputRef} />
}
Reference resources :
边栏推荐
猜你喜欢
简易Shader实践记录5-屏幕渐变
CMake系列教程2-HelloWorld
Elk+filebeat搭建分布式日志
【机器学习】降维技术-PCA
【 apprentissage automatique】 regroupement kmeans
看界面控件DevExpress WinForms——如何自定义辅助功能属性(下)
String类常用方法
[machine learning] hierarchical clustering
[paper notes] modeling task relationships in multi task learning with multi gate mixture of experts
Introduction and simple application of CGI
随机推荐
B站自定义倍数代码
DAY 5 (数组)
防止静态反编译及动态反调试,反外挂
MySQL storage engine Encyclopedia
Alibaba cloud toolkit one click automatic deployment of jar packages
CMake系列教程1-初始CMake
jdbc 02: 连接mysql,并实现删除与更新
Sign up now | how to reduce the cost of cloud data analysis?
Matplotlib (VI) 3D mapping
大小端模式说明
Use of delete
剑指 Offer 47. 礼物的最大价值
如何选择加壳工具?
高效开发工具使用技巧
anaconda安装Labelimg(超简单可用)
使用VideoView实现视频轮番播放
[paper notes] modeling task relationships in multi task learning with multi gate mixture of experts
layaAir 实践初探
Tensorflow Serving部署tensorflow、keras模型详解
简易Shader实践记录5-屏幕渐变