App.js的代码
06是函数组件
07是类组件
import React, { useEffect, useRef } from 'react';
import LearnFunction06 from './LearnFunction06'; // 函数组件和类组件的ref使用方式
import LearnFunction07 from './LearnFunction07'; // 函数组件和类组件的ref使用方式
export default function BoxReact() {const learnRef = useRef(null)const classRef = useRef(null)useEffect(() => {console.log(learnRef.current);console.log(classRef.current);}, [])return (<div><LearnFunction06 ref={learnRef}></LearnFunction06><LearnFunction07 ref={classRef}></LearnFunction07></div>)
}
06的代码
import React, { forwardRef } from 'react'export default forwardRef(function LearnFunction06(props, ref) {return (<div ref={ref}> LearnFunction06</div>)
})
正常函数组件是没有ref的,需要通过forwardRef来修饰组件才能产生ref
07的代码
import React, { Component } from 'react'export default class LearnFunction07 extends Component {render() {return (<div>LearnFunction07</div>)}
}
效果图
这样都可以拿到ref啦