前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >React技巧之调用子组件函数

React技巧之调用子组件函数

作者头像
chuckQu
发布2022-08-19 15:47:58
1.8K0
发布2022-08-19 15:47:58
举报
文章被收录于专栏:前端F2E

原文链接:https://bobbyhadz.com/blog/react-call-function-in-child-component[1]

作者:Borislav Hadzhiev[2]

正文从这开始~

forwardRef

在React中,从父组件中调用子组件的函数:

  1. forwardRef 中包裹一个子组件。
  2. 在子组件中使用useImperativeHandle钩子,来为子组件添加一个函数。
  3. 在父组件中使用ref来调用子组件的函数。比如说,childRef.current.childFunction()
代码语言:javascript
复制
import {forwardRef, useImperativeHandle, useRef} from 'react';

const Child = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    childFunction1() {
      console.log('child function 1 called');
    },
    childFunction2() {
      console.log('child function 2 called');
    },
  }));

  return (
    <div>
      <h2>child content</h2>
    </div>
  );
});

export default function Parent() {
  const childRef = useRef(null);

  const handleClick = () => {
    childRef.current.childFunction1();

    childRef.current.childFunction2();
  };

  return (
    <div>
      <Child ref={childRef} />

      <h2>parent content</h2>

      <button onClick={handleClick}>Call child functions</button>
    </div>
  );
}

call-child-function-from-parent.gif

我们使用forwardRef 将父组件的ref转发给子组件。forwardRef 方法接收一个函数,该函数接收propsref作为参数。

传递给forwardRef 的函数应该返回一个React节点。

我们需要转发ref到子组件,这样我们就可以使用useImperativeHandle钩子来自定义子组件的实例值,当使用ref时,该实例值被公开给父组件。

代码语言:javascript
复制
useImperativeHandle(ref, () => ({
  childFunction1() {
    console.log('child function 1 called');
  },
  childFunction2() {
    console.log('child function 2 called');
  },
}));

渲染<Child ref={childRef} />的父组件,将能够以childRef.current.childFunction1()的方式来调用childFunction1

或者,你可以使用更间接的方法。

useEffect

在React中,从父组件中调用子组件的函数:

  1. 在父组件中声明一个count state 变量。
  2. 在子组件中,添加count变量为useEffect钩子的依赖。
  3. 在父组件中增加count变量的值,以重新运行子组件的useEffect
代码语言:javascript
复制
import {useEffect, useState} from 'react';

const Child = ({count}) => {
  useEffect(() => {
    const childFunction1 = () => {
      console.log('child function 1 called');
    };

    const childFunction2 = () => {
      console.log('child function 2 called');
    };

    // 👇️ don't run on initial render
    if (count !== 0) {
      childFunction1();

      childFunction2();
    }
  }, [count]);

  return (
    <div>
      <h2>child content</h2>
    </div>
  );
};

export default function Parent() {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(current => current + 1);
  };

  return (
    <div>
      <Child count={count} />

      <h2>parent content</h2>

      <button onClick={handleClick}>Call child functions</button>
    </div>
  );
}

父组件声明了一个count state 变量,将其作为子组件的属性来传递给子组件。

我们将count变量添加到useEffect钩子的依赖项中。每当count值更新时,我们传递给useEffect 的函数将会运行。

代码语言:javascript
复制
useEffect(() => {
  const childFunction1 = () => {
    console.log('child function 1 called');
  };

  const childFunction2 = () => {
    console.log('child function 2 called');
  };

  // 👇️ don't run on initial render
  if (count !== 0) {
    childFunction1();

    childFunction2();
  }
}, [count]);

useEffect 钩子中,子组件声明并调用了两个函数。父组件可以通过改变count state 变量的值,来运行子组件中useEffect里的逻辑。

需要注意的是,我们在调用useEffect 里的函数之前,检查count的值是否不等于0。

当组件挂载时,每当组件的依赖项发生变化时,useEffect 就会运行。如果你不想在挂载阶段运行useEffect 里的逻辑,在调用函数之前,检查count变量的值是否不等于0。

参考资料

[1]

https://bobbyhadz.com/blog/react-call-function-in-child-component: https://bobbyhadz.com/blog/react-call-function-in-child-component

[2]

Borislav Hadzhiev: https://bobbyhadz.com/about

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-06-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 前端F2E 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • forwardRef
  • useEffect
    • 参考资料
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档