注意:①需使用hooks函数组件 ②使用了antDesign组件库(可不用)
如何使用
父组件代码
import React, { useState, useRef, useEffect } from 'react';
import { Button } from 'antd';
import Child from './components/child';export default () => {const childRef = useRef();//使用ref调用子组件的方法const handleOpen = () => {childRef.current.showModal('Hello word');};return (<div><Button type="primary" onClick={handleOpen}>点我</Button><Child ref={childRef} /></div>);
};
子组件代码
import React, { useImperativeHandle, forwardRef, useState, useRef, useEffect } from 'react';
import { Modal } from 'antd';const ChildComponent = forwardRef((props, ref) => {const [isModalOpen, setIsModalOpen] = useState(false);const [data, setData] = useState('');//弹框打开const showModal = async (data) => {setIsModalOpen(true);setData(data);};//弹框确定const handleOk = async () => {setIsModalOpen(false);};//弹框取消const handleCancel = () => {setIsModalOpen(false);};// 通过第二个参数ref来控制暴露哪些方法useImperativeHandle(ref, () => ({showModal,}));return (<div><Modal title="子组件" width={800} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}><div>{data}</div></Modal></div>);
});export default ChildComponent;
注:本人前端小白 ,如有不对的地方还请多多指教