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;
相关推荐
zzzzzz3103 分钟前
别急着把动效组件搬进页面:从 react-bits 看 React 动效库该怎么评估
前端·react.js·开源
李姆斯7 小时前
为啥Agent在coding表现这么好,但是在别的领域就是差的不少?
前端·agent·ai编程
鱼与宇10 小时前
前端Web(html+css+js+vue3)
前端
雪芽蓝域zzs11 小时前
(六)打包优化 + Nginx 部署完整配置 + 项目收尾
前端·vue.js
研☆香11 小时前
聊一聊前端的常见字 关键字
开发语言·前端·javascript
东风破_12 小时前
JWT 1:从一个登录请求开始,理解 React 项目里的 API 层与 Mock
前端·后端
东风破_12 小时前
JWT 3:为什么 Token 要放进 Authorization?Axios 拦截器到底解决了什么?
前端·后端
东风破_12 小时前
JWT 5:路由守卫是什么?把整个 JWT 登录鉴权流程串起来
前端·后端
东风破_12 小时前
JWT 2:HTTP 是无状态的,为什么登录成功后还要给 Token?
前端·后端
东风破_12 小时前
JWT 4:Zustand 到底解决了什么?为什么登录状态要放进 Store?
前端·后端