React-Hooks 指南

3 minute read

React Hooks 含义

为函数组件提供钩子以实现外部功能,如添加状态

React 默认提供的四个最常用的钩子

1useState()  //状态
2
3useEffect()    //函数副作用
4useContext()
5useReducer()

更多的 Hook包括

1useReducer
2useCallback
3useMemo
4useRef
5useImperativeHandle
6useLayoutEffect
7useDebugValue
8自定义Hook

useImperativeHandle

Typescript中搭配useImperativeHandle 和 forwardRef使用

 1export interface MyInputHandles {
 2  focus(): void;
 3}
 4
 5const MyInput: RefForwardingComponent<MyInputHandles, MyInputProps> = (
 6  props,
 7  ref
 8) => {
 9  const inputRef = useRef<HTMLInputElement>(null);
10
11  useImperativeHandle(ref, () => ({
12    focus: () => {
13      if (inputRef.current) {
14        inputRef.current.focus();
15      }
16    },
17  }));
18
19  return <input {...props} ref={inputRef} />;
20};
21
22export default forwardRef(MyInput);

建议useImperativeHandle和forwardRef同时使用,减少暴露给父组件的属性,避免使用 ref 这样的命令式代码 import { useRef,forwardRef,MutableRefObject,useImperativeHandle,Ref} from “react”;

 1//只暴露value、getType、focus给父级
 2const InputEl = forwardRef((props: {}, ref: Ref<any>): JSX.Element=>{
 3    const inputEl: MutableRefObject<any> = useRef();
 4
 5    useImperativeHandle(ref, ()=>({//第一个参数:暴露哪个ref;第二个参数:暴露什么
 6        value: (inputEl.current as HTMLInputElement).value,
 7        getType: () => (inputEl.current as HTMLInputElement).type,
 8        focus: () => (inputEl.current as HTMLInputElement).focus()
 9    }));
10
11    return(
12        <input ref={inputEl} type="text" {...props}/>
13    )
14})
15//暴露整个input节点给父级
16const InputEl = forwardRef((props: {}, ref: Ref<any>): JSX.Element=>{
17    return(
18        <input ref={ref} type="text" {...props}/>
19    )
20});
21
22//父级
23function InputWithFocusButton() {
24    const inputEl: MutableRefObject<any> = useRef(null);
25
26    function onButtonClick() {
27        console.log('子组件input的对象:', inputEl.current);
28        inputEl.current.focus();
29    };
30    return (
31        <>
32            <InputEl ref={inputEl} />
33            <button onClick={onButtonClick}>Focus the input</button>
34        </>
35    );
36}

复制代码通过forwardRef,父组件获取子组件的ref,子组件在暴露ref中,限制暴露的一些参数

*自定义hooks,封装重复使用的代码,可以抽离出成一个模块,在多个场景下使用,提高代码的复用性

参考:
React Hook 最佳实践 https://blog.csdn.net/weixin_43902189/article/details/99689963
React 文档
useEffect完全指南 video React Hook FAQ