在 React
中,如果使用的是类组件可以通过 this.ref.current.state
直接获取绑定 ref
后子组件中的状态。但是函数组件无法这样直接获取子组件中的状态。
通过之前介绍过的 forwardRef 和 useImperativeHandle
也可以轻松的在函数组件中获取到子组件的状态。
方法:通过 forwardRef 和 useImperativeHandle
子组件
import React, { forwardRef, useState, useImperativeHandle } from 'react';
const ChildComponent = (props, ref) => {
const [state, setState] = useState('Initial state');
useImperativeHandle(ref, () => {
return {
// 暴露函数中,返回组件状态
getState() {
return state
}
}
})
// ...
};
export default forwardRef(ChildComponent);
父组件
import React, { useRef } from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const childRef = useRef();
const handleClick = () => {
// 通过 ref 调用子组件的函数获取到子组件中的状态
console.log(childRef.current?.getState())
}
return (
<div>
<button onClick={handleClick}>获取子组件状态</button>
<ChildComponent ref={childRef} />
</div>
);
};
export default ParentComponent;
注意:这种通过 ref
操作和获取子组件状态的方法是比较不通用的做法,在一些特定场景中较适用。应该还是尽量通过 props
传递和回调函数中获取和控制子组件状态。