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;
相关推荐
卷帘依旧21 分钟前
JavaScript 闭包经典问题:为什么输出 10 次 i=10
javascript
柳杉40 分钟前
Three.js × Blender:从建模到 Web 3D 的完整工作流深度解析
前端·javascript·数据可视化
reembarkation2 小时前
vue3中使用howler播放音频列表
前端·vue.js·音视频
手握风云-2 小时前
基于 Java 的网页聊天室(三)
服务器·前端·数据库
weixin199701080162 小时前
《识货商品详情页前端性能优化实战》
前端·性能优化
Forever7_2 小时前
重磅!Vue3 手势工具正式发布!免费使用!
前端·前端框架·前端工程化
用户806138166592 小时前
发布为一个 npm 包
前端·javascript
树上有只程序猿2 小时前
低代码何时能出个“秦始皇”一统天下?我是真学不动啦!
前端·后端·低代码
TT_哲哲3 小时前
小程序双模式(文件 / 照片)上传组件封装与解析
前端·javascript
菜果果儿3 小时前
Vue 3 + TypeScript 常用代码示例总结
前端