赞
踩
在vue3中,
defineExpose
暴露出父组件需要访问的 变量
或 方法
ref
函数定义子组件的 refName
,并通过 refName.value.xxx
继续访问可使用 useImperativeHandle
、forwardRef
、useRef
useImperativeHandle
定义要暴露出去的内容,第一个参数是 refforwardRef
包裹 App 组件后,再暴露出去import React, { useState, useImperativeHandle, forwardRef } from "react";
import { Modal, Button } from "antd";
const App = (props, ref) => {
const [isModalOpen, setIsModalOpen] = useState(false);
const [data, setData] = useState({});
const showModal = () => {
setIsModalOpen(true);
};
const handleCancel = () => {
setIsModalOpen(false);
};
// 暴露给父组件访问(useImperativeHandle、forwardRef、ref组合使用)
useImperativeHandle(ref, () => ({
openModal: (data) => {
showModal();
setData(data);
},
}));
return (
<Modal
title="查看平台详情"
open={isModalOpen}
onCancel={handleCancel}
width={700}
footer={null}
>
<div>
<Button type="primary" onClick={handleOk}>
确定
</Button>
</div>
</Modal>
);
};
const Index = forwardRef(App);
export default Index;
这一步跟vue3比较接近
useRef
定义子组件的 ref
属性refName.current.xx
再继续访问子组件暴露出的内容import React, { useRef } from "react";
import { Button } from "antd";
import Title from "../components/Title";
import DetailModal from "../components/DetailModal";
// 渲染
const App = () => {
const detailRef = useRef();
// 查看详情
function handleDetail(row) {
detailRef.current.openModal(row);
}
return (
<>
<Title title="境内平台管理">
<Button type="primary">新建平台</Button>
</Title>
<DetailModal ref={detailRef} />
</>
);
};
export default App;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。