React 函数式组件之父组件调用子组件的方法

本文介绍在React中如何让父组件调用子组件的方法,通过使用useRef和forwardRef结合useImperativeHandle实现跨组件通信,提供了一个清晰的实践案例。

前言:

最近做一个React项目,所有组件都使用了函数式组件,遇到一个父组件调用子组件方法的问题,让我好一阵头疼。

我们都知道,React 中子组件调用父组件方法,使用 props 传递过来就可以在子组件中使用。但是父组件如何调用子组件方法呢?请看下面代码:

第一步:

在父组件中,使用 useRef 创建一个 ref

import { useRef } from 'react'
// 父组件中代码
const FCom = () => {
    const cRef = useRef(null);
    return (
        <div>
            <ChildCom ref={cRef} />
        </div>
    )
    
}

第二步:

子组件中代码:(使用了 forwardRefuseImperativeHandle

import { forwardRef, useImperativeHandle } from 'react'
const ChildCom = forwardRef(({
  // 这里是一些props参数
}, ref) => {
    useImperativeHandle(ref, () => ({
        getData: getData,
        otherFun: otherFun
    }))
    function getData() {
        // to do something
    }
    function otherFun() {
        console.log('这是其他方法')
    }
    return (
        <div>子组件</div>
    )
})

第三步:

此时,在父组件中就可以随心所欲的调用子组件中的方法了!

import { useRef } from 'react'
// 修改父组件中代码
const FCom = () => {
    const cRef = useRef(null);
    const handleClick = () => {
        cRef.current && cRef.current.getData()
    }
    return (
        <div>
            <ChildCom ref={cRef} />
        </div>
    )
    
}

好了,如果你看完觉得有收获,帮我点个赞哦~ 谢谢~

下面是我的博客,欢迎来逛

React 函数式组件之父组件调用子组件的方法https://www.cikayo.com/article/149

### React父组件调用子组件方法的实现方式 在 React 开发中,父组件可以通过多种方式来调用子组件方法。以下是几种常见的实现方式: #### 1. 使用 Refs 调用子组件方法 通过 `React.createRef()` 创建一个 ref 对象,并将其传递给子组件父组件可以通过这个 ref 访问子组件实例及其公开的方法。 ```javascript // Parent.js import React from 'react'; import Child from './Child'; class Parent extends React.Component { constructor(props) { super(props); this.childRef = React.createRef(); } callChildMethod = () => { if (this.childRef.current) { this.childRef.current.sendMessage(); // 调用子组件方法 } }; render() { return ( <div> <button onClick={this.callChildMethod}>Call Child Method</button> <Child ref={this.childRef} /> </div> ); } } export default Parent; // Child.js import React, { Component } from 'react'; class Child extends Component { sendMessage = () => { console.log('Message sent from child component'); }; render() { return <span>Child</span>; } } export default Child; ``` 这种方式适用于类组件[^2]。 --- #### 2. 使用回调函数调用子组件方法 子组件可以在其生命周期方法(如 `componentDidMount`)中将自身的实例或特定方法通过 props 回传给父组件父组件保存该引用后即可调用子组件方法。 ```javascript // Child.js import React, { Component } from 'react'; class Child extends Component { sendMessage = () => { console.log('Sending message from child'); }; componentDidMount() { this.props.onChildEvent(this); // 将子组件实例回传给父组件 } render() { return <span>Child</span>; } } export default Child; // Parent.js import React, { Component } from 'react'; import Child from './Child'; class Parent extends Component { childInstance = null; setChildInstance = (child) => { this.childInstance = child; }; callChildMethod = () => { if (this.childInstance && typeof this.childInstance.sendMessage === 'function') { this.childInstance.sendMessage(); // 调用子组件方法 } }; render() { return ( <div> <button onClick={this.callChildMethod}>Call Child Method</button> <Child onChildEvent={this.setChildInstance} /> </div> ); } } export default Parent; ``` 这种方法不需要使用 refs,适合某些场景下的解耦需求[^5]。 --- #### 3. 函数组件中使用 forwardRef 和 useImperativeHandle 对于函数式组件,可以直接使用 `useImperativeHandle` 来暴露方法父组件访问。 ```javascript // Child.js import React, { useRef, useImperativeHandle } from 'react'; const Child = React.forwardRef((props, ref) => { const childFunction = () => { console.log('This is a method exposed to the parent.'); }; useImperativeHandle(ref, () => ({ func: childFunction, })); return <span>Child</span>; }); export default Child; // Parent.js import React from 'react'; import Child from './Child'; function Parent() { const childRef = React.useRef(null); const handleChild = () => { if (childRef.current?.func) { childRef.current.func(); // 调用子组件方法 } }; return ( <> <div onClick={handleChild}>Call Child Function</div> <Child ref={childRef} /> </> ); } export default Parent; ``` 此方法允许函数式组件像类组件一样被操作,同时保持良好的封装性[^4]。 --- #### 4. 利用 Context API 进行跨层通信 如果父子组件之间存在多级嵌套关系,可以考虑使用 Context API 实现更灵活的通信机制。 ```javascript // MyContext.js import React from 'react'; const MyContext = React.createContext(); export const MyProvider = ({ children }) => { const sendMessage = () => { console.log('Message sent via context'); }; return ( <MyContext.Provider value={{ sendMessage }}> {children} </MyContext.Provider> ); }; export const useContextAPI = () => React.useContext(MyContext); ``` ```javascript // Parent.js import React from 'react'; import { MyProvider } from './MyContext'; import Child from './Child'; function Parent() { return ( <MyProvider> <Child /> </MyProvider> ); } export default Parent; // Child.js import React from 'react'; import { useContextAPI } from './MyContext'; function Child() { const { sendMessage } = useContextAPI(); return ( <div> <button onClick={sendMessage}>Send Message via Context</button> </div> ); } export default Child; ``` 这种方式更适合复杂的跨层级交互场景[^3]。 --- ### 总结 以上四种方式各有优劣: - **Refs** 提供了一种简单直接的方式,但可能破坏组件的独立性和可测试性。 - **回调函数** 更加显式化,有助于减少不必要的依赖注入。 - **forwardRef + useImperativeHandle** 是现代函数式组件的最佳实践之一。 - **Context API** 可用于复杂的应用架构设计,尤其当涉及深层嵌套时更为适用。 每种方案的选择应基于具体业务需求和技术背景综合考量。
评论 11
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值