父组件向子组件传入ref
import { useRef } from 'react';
import ChildrenModal from './ChildrenModal';
const parent = () => {
const childrenRef = useRef(null);
return (
<>
<ChildrenModal ref={childrenRef} />
</>
);
};
export default parent;
子组件为ref绑定方法
import { Modal } from 'antd';
import { useState, useImperativeHandle, forwardRef } from 'react';
export default forwardRef((props, ref) => {
const [isModalVisible, setIsModalVisible] = useState(false);
const showModal = () => {
setIsModalVisible(true);
};
useImperativeHandle(ref, () => ({
showModal,
}));
return (
<Modal
title="Basic Modal"
visible={isModalVisible}
onCancel={() => {
setIsModalVisible(false);
}}
>
<p>Some contents...</p>
</Modal>
);
});
父组件调用ref上的方法
import { useRef } from 'react';
import { Button } from 'antd';
import ChildrenModal from './ChildrenModal';
const parent = () => {
const childrenRef = useRef(null);
return (
<>
<Button
type="link"
onClick={() => {
childrenRef.current.showModal();
}}
>
点击显示modal
</Button>
<ChildrenModal ref={childrenRef} />
</>
);
};
export default parent;