Skip to content

React Hooks 中父组件调用子组件方法

Published: at 10:03 AMSuggest Changes

需求

React 父组件主动触发子组件的方法

解决方法

主要用到了 useRef useImperativeHandle forwardRef 3 个方法

子组件代码如下,用 useImperativeHandle 将方法暴露出去

import React, { useState, useImperativeHandle, forwardRef } from 'react';
import { MyComponent } from 'my-component';

const Children = forwardRef((props, ref) => {
  const [myState, setMyState] = useState([]);
  useImperativeHandle(
    ref,
    () => ({
      myState,
      setMyState,
    }),
    [myState]
  );
  return <MyComponent {...props} />;
});

export default Children;

父组件代码如下,主要是用 useRef

import React, { useState, useRef } from 'react';
import Children from 'children';

const Parent = (props, ref) => {
  const [ref] = useRef(null);

  const setState = (params) => {
    ref.current.setMyState(params);
  };

  const getState = () => {
    console.log('getState :>> ', ref.current.myState);
  };

  return (
    <div>
      <div
        onClick={() => {
          setState(1111);
        }}>
        setState
      </div>
      <div
        onClick={() => {
          getState();
        }}>
        getState
      </div>
      <Children ref={ref} />
    </div>
  );
};

后记

这个最好看一下 react 官方文档


Previous Post
ESLint 忽略特定文件和目录
Next Post
Webpack 引入 SVG 文件