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;
相关推荐
nn_(nana)19 分钟前
修改文件权限--- chmod ,vi/vim,查看文件内容,yum-软件包管理器,systemctl管理系统服务
前端
汪汪队立大功12325 分钟前
JavaScript是怎么和html元素关联起来的?
开发语言·javascript·html
烛阴1 小时前
从零开始掌握C#核心:变量与数据类型
前端·c#
han_1 小时前
前端高频面试题之Vuex篇
前端·vue.js·面试
qq_415216252 小时前
vue3搭建项目yarn+vue3+webpack+less+element-plus
前端·webpack·less
天天向上10242 小时前
VueUse的使用
前端·vue.js·vscode
猪猪拆迁队3 小时前
前端图形引擎架构设计:双引擎架构设计
前端·后端·架构
宋辰月3 小时前
学习react第三天
前端·学习·react.js
bug总结3 小时前
更新原生小程序封装(新增缓存订阅)完美解决
前端·缓存·小程序
GISer_Jing3 小时前
Node.js 开发实战:从入门到精通
javascript·后端·node.js