父组件获取子组件数据:
import React, { useState, useImperativeHandle, useRef, forwardRef } from 'react'
import ReactDOM from 'react-dom'
// 1: 函数组件没有实例 需要用forwardRef包装
const Child = forwardRef((props, childRef) => {
const [state, setstate] = useState({ name: 'superTiger' })
//2: return后面即为暴露给父组件的值 这里即为state
useImperativeHandle(childRef, () => state)
return (
<div>
<span>{state?.name}</span>
</div>
)
})
const App = () => {
const childRef = useRef()
const getChildData = () => {
console.log('获取到的子组件数据为:', childRef.current)
}
return (
<>
{/* 给子组件添加ref属性 */}
<Child ref={childRef} />
<button
onClick={() => {
getChildData()
}}
>
子组件数据
</button>
</>
)
}
ReactDOM.render(<App />, document.getElementById('root'))