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;
相关推荐
蓝婷儿12 分钟前
第二章:CSS秘典 · 色彩与布局的力量
前端·css
flying robot14 分钟前
js在浏览器执行原理
开发语言·javascript·ecmascript
Wyc724091 小时前
HTML:入门
前端·html
Sunny_lxm1 小时前
自定义列甘特图,原生开发dhtmlxgantt根特图,根据数据生成只读根特图,页面展示html demo
前端·html·甘特图·dhtmlxgantt
熊猫钓鱼>_>2 小时前
建筑IT数字化突围:建筑设计企业的生存法则重塑
前端·javascript·easyui
GISer_Jing4 小时前
前端性能指标及优化策略——从加载、渲染和交互阶段分别解读详解并以Webpack+Vue项目为例进行解读
前端·javascript·vue
不知几秋4 小时前
数字取证-内存取证(volatility)
java·linux·前端
水银嘻嘻6 小时前
08 web 自动化之 PO 设计模式详解
前端·自动化
Zero1017137 小时前
【详解pnpm、npm、yarn区别】
前端·react.js·前端框架
&白帝&8 小时前
vue右键显示菜单
前端·javascript·vue.js