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;
相关推荐
李白的天不白几秒前
webpack 与 vue-loader 版本冲突问题
前端·vue.js·webpack
sunneo5 分钟前
专栏D-团队与组织-05-冲突与决策
前端·人工智能·产品运营·aigc·产品经理·ai-native
空中海7 分钟前
05 React Native架构设计、主线项目与专家实践
javascript·react native·react.js
舟遥遥娓飘飘10 分钟前
量化投资体系之二:为 Web 看板集成公众号/财经原始数据
前端·数据分析·自动化·ai编程
ZC跨境爬虫12 分钟前
跟着 MDN 学 HTML day_13:多媒体嵌入 —— 视频与音频
前端·css·笔记·ui·html·音视频
之歆13 分钟前
DAY12_CSS3选择器全攻略 + 盒子新特性完全指南(上)
前端·css·css3
之歆15 分钟前
DAY13_CSS3进阶完全指南 —— 背景、边框、文本、渐变、滤镜与 Web 字体(上)
前端·c#·css3
幸福巡礼22 分钟前
【 LangChain 1.2 实战(四)】构建一个模块化的天气查询 Agent
java·前端·langchain
小满zs1 小时前
Next.js精通SEO第四章(JSON-LD + web vitals)
前端·seo·next.js
云水一下9 小时前
从零开始!VMware安装Fedora Workstation 44桌面系统完整教程
前端