react父组件往孙子组件传值Context API

时间:2025-05-14 19:38:26

步骤:
创建一个 Context
在父组件中用 Provider 提供值
在孙子组件中用 useContext 消费值

// 创建 Context
const MyContext = React.createContext();

// 父组件
const Parent = () => {
  const value = "Hello from parent";
  return (
    <MyContext.Provider value={value}>
      <Child />
    </MyContext.Provider>
  );
};

// 子组件(无需关心 value)
const Child = () => {
  return <GrandChild />;
};

// 孙子组件
const GrandChild = () => {
  const value = React.useContext(MyContext);
  return <div>{value}</div>;
};

React.forwardRef + useImperativeHandle 实现子组件暴露方法

const ChildComponent = forwardRef((props, ref) => {
  const [inputValue, setInputValue] = useState('');

  useImperativeHandle(ref, () => ({
    clearInput: () => setInputValue(''),
  }));

  return <input value={inputValue} onChange={(e) => setInputValue(e.target.value)} />;
});

父组件调用:

const childRef = useRef();
<ChildComponent ref={childRef} />
<button onClick={() => childRef.current?.clearInput()}>Clear</button>```