Function Ref 组件, 实现子组件提供,state,以及处理方法
/** SonDOM.tsx */
interface UploadProps {
length?: number;
accept?: string;
size?: number;
}
export interface UploadRef {
getImageList: () => string[];
}
function SonDOM(props: UploadProps, ref: React.Ref<any>) {
const [imgData, setImgData] = React.useState({
previewVisible: false,
previewTitle: '',
previewImage: '',
});
React.useImperativeHandle(ref, () => ({
getImageList: () => {
return Object.values(imageList);
},
}));
return <div>{{imgData.previewTitle}}</div>
}
export default React.forwardRef(SonDOM);
/** ParentDOM */
export default function ParentDOM() {
const actionRef = React.useRef<UploadRef>();
return <div>
<SonDOM ref={actionRef} />
<button onClick={() => {
if (actionRef.current) {
const imageList = actionRef.current.getImageList();
}
}}>按钮<button>
</div>
}