You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React.js中如何在InfoDialog的onClose回调内为handleShowData传参

React 弹窗onClose回调传参解决方案

要给handleShowData传递入参,根据你参数的来源不同,有两种常见实现方式:

方式1:参数来自当前组件已存储的状态/变量

你打开InfoDialog弹窗时,必然是基于某个节点的操作触发的,你可以在触发弹窗打开时把需要的nodeData和data存入当前组件的状态,在onClose触发时直接取用即可:

// 新增状态存储弹窗关联的参数
const [currentNode, setCurrentNode] = useState(null);
const [currentData, setCurrentData] = useState(null);

// 打开弹窗的触发逻辑,比如点击节点时调用
const handleOpen = (node, data) => {
  setCurrentNode(node);
  setCurrentData(data);
  setIsOpenDialog(true);
};

// InfoDialog 调用示例
<InfoDialog
  open={isOpenDialog}
  labelButtonOk="OK"
  onClose={() => {
    handleShowData(currentNode, currentData);
    // 可选:关闭后清空状态
    setCurrentNode(null);
    setCurrentData(null);
  }}
  title={titleDialog}
/>

如果要优化渲染性能,可以用useCallback包装关闭逻辑,避免每次渲染生成新的匿名函数:

const handleDialogClose = useCallback(() => {
  handleShowData(currentNode, currentData);
  setCurrentNode(null);
  setCurrentData(null);
}, [currentNode, currentData]);

// 组件调用
<InfoDialog
  open={isOpenDialog}
  labelButtonOk="OK"
  onClose={handleDialogClose}
  title={titleDialog}
/>

方式2:参数由InfoDialog组件的onClose回调返回

如果你使用的InfoDialog组件本身设计为关闭时会向外抛出需要的nodeData和data参数,直接在回调中接收参数传递即可:

<InfoDialog
  open={isOpenDialog}
  labelButtonOk="OK"
  onClose={(nodeData, data) => handleShowData(nodeData, data)}
  title={titleDialog}
/>

内容的提问来源于stack exchange,提问作者Josley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 15:54:00