Skip to content

09.useRef应用案例及源码实现

案例

js
import { useRef } from 'react';
export default function Form() {
  const inputRef = useRef(null);

  function handleClick() {
    inputRef.current.focus();
  }

  return (
    <div>
      <input ref={inputRef} />
      <button onClick={handleClick}>
        Focus the input
      </button>
    </div>
  );
}

源码

js
export function useRef(initialValue) {
  states[hookIndex] = states[hookIndex] || { current: initialValue }
  return states[hookIndex++]
}

基于 VitePress 构建