Published on

React一些有用hook或api

Authors

flushSync

作用:可以使用flushSync强制 React 同步更新(“刷新”)DOM

用法:

import { flushSync } from "react-dom";
flushSync(() => {
  setTodos([ ...todos, newTodo]);
});

forwardRef 和 useImperativeHandle

forwardRef

作用:

  • 参考
    • forwardRef(render)
    • render函数
  • 用法
    • 将dom节点暴露给父组件
    • 在多个组件中转发ref
    • 暴露命令式句柄而非dom节点

import { forwardRef } from 'react';

const MyInput = forwardRef(function MyInput(props, ref) {
  const { label, ...otherProps } = props;
  return (
    <label>
      {label}
      <input {...otherProps} ref={ref} />
    </label>
  );
});

export default MyInput;

useImperativeHandle

作用:

  • 参考
    • useImperativeHandle(ref, createHandle, dependencies?)
  • 使用方法
    • 向父组件暴露一个自定义的ref句柄
    • 暴露自己的命令式的方法
import { forwardRef, useRef, useImperativeHandle } from 'react';

const MyInput = forwardRef(function MyInput(props, ref) {
  const inputRef = useRef(null);

  useImperativeHandle(ref, () => {
    return {
      focus() {
        inputRef.current.focus();
      },
      scrollIntoView() {
        inputRef.current.scrollIntoView();
      },
    };
  }, []);

  return <input {...props} ref={inputRef} />;
});