父组件
import ForwardChild from './forwardChild'
import {
useRef, useEffect} from 'react'
function Forward () {
const child = useRef()
useEffect(() => {
console.log(child.current) // 打印获取到元素
}, [])
return (
<h1>我是ForWard
<ForwardChild ref={
child}></ForwardChild>
</h1>
)
}
export default Forward
子组件
function ForwardChild () {
return (
<div>我是child</div>
)
}
export default ForwardChild
打印结果报 react_devtools_backend.js:4026 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
原因,函数式组件不能用此方法获取dom元素。
解决办法
- 在子组件使用 forwardRef的方法暴露出dom
import {
forwardRef} from 'react'
function ForwardChild (props, _ref) {
return (
<div ref={
_ref}>我是child</div> // 暴露出div的dom元素
)
}
export default forwardRef((props, _ref) => {
return ForwardChild(props, _ref)
})
- 使用useImperativeHandle 的hook 暴露出dom给父元素
import {
forwardRef, useImperativeHandle, useRef} from 'react'
function ForwardChild (props, _ref) {
const {
refDom} = props // 需要父组件暴露给子组件一个ref对象
const div = useRef()
useImperativeHandle(refDom, () => ({
div
})) // 第一个参数是父组件穿过来的ref,第二个参数传递给父组件的dom
return (
<div ref={
div}>我是child</div>
)
}
// export default forwardRef((props, _ref) => {
// return ForwardChild(props, _ref)
// })
export default ForwardChild