react中ref使用支持父调用子组件的方法

父组件不管是类还是函数组件都支持creatRef(),函数组件可以用useRef();
子组件中,函数组件由于没有实例,只能使用forwardRef搭配useImperativeHandle使用

javascript 复制代码
import React, { createRef,forwardRef} from 'react'
import styles from './index.module.scss'
import { useImperativeHandle } from 'react';
import { useRef } from 'react';

class Test extends React.PureComponent {
  test() {
    console.log("Test111");
  }
  render() {
    return <h2>Test</h2>;
  }
}
// 创建一个函数组件, 作为子组件测试
// 使用forwardRef将函数包裹起来
const Foo = forwardRef(function(props, ref) {
  const testfoo = () => {
    console.log('testfoo');
  }
  useImperativeHandle(ref, () => {
    return {
      testfoo
    }
  },[])
  return (
    <h2 ref={ref}>Foo</h2>
  )
})

// export default class About extends React.Component{
//   constructor(){
//     super()
//     this.testRef = createRef();
//     this.fooRef = createRef();
//   }
//   getDom() {
//     this.testRef.current.test();
//     console.log(this.fooRef.current,'current');
//     this.fooRef.current.testfoo();
//   }
//   render() {
//     return (
//       <div>
//         <Test ref={this.testRef}/>
//         <Foo  ref={this.fooRef}/>
//         <button onClick={() => this.getDom()}>获取DOM</button>
//       </div>
//     )
//   }
// }


const About = () => {
  // const testRef = useRef();
  // const fooRef = useRef();
  const testRef = createRef();
  const fooRef = createRef();
  const getDom = () => {
    testRef.current.test();
    fooRef.current.testfoo();
  }
  return (
    <div>
      <Test ref={testRef}/>
      <Foo  ref={fooRef}/>
      <button onClick={getDom}>获取DOM</button>
    </div>
  )
}
export default About;
相关推荐
huakoh4 分钟前
MCP 到底解决了什么问题:从协议设计到官方 Python SDK 最小实现
前端
用户059540174466 分钟前
用了半年 LangChain Memory,才发现记忆总“串台”——3 个自动化测试避坑指南
前端·css
大爱编程♡7 分钟前
Vue3基础
前端·javascript·vue.js
weedsfly10 分钟前
防抖与节流:从原理到 React Hook 封装
前端·javascript·面试
甜味弥漫10 分钟前
React 从类组件到 Hooks:为什么 Hooks 改变了 React?
前端·javascript·react.js
天蓝色的鱼鱼17 分钟前
让 AI 写代码半年后,我发现了几个藏在项目里的安全隐患
前端·javascript·ai编程
随风一样自由33 分钟前
【前端+跨端技术新格局】Tauri vs Electron 完整性能对比(2026实测数据+底层原理)
前端·javascript·electron
L-影39 分钟前
Pydantic 模型:为你的 Web 数据装上“安检系统”
前端
Reload.1 小时前
GJ航司,验证码网易易盾 JS逆向 纯算轨迹
开发语言·前端·javascript
L-影1 小时前
FastAPI 请求头与 Cookie:Web 世界的“身份证”与“通行证”
前端·fastapi