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

基于React-Google-Apps-Script,如何从侧边栏触发带参模态框?

从Google Docs插件侧边栏触发带参数模态窗口的实现方案

完全可以实现这个需求,下面是具体的步骤和代码示例:

1. 修改服务器端openDialog函数,支持接收并传递key参数

修改你的服务器端函数,让它接收itemKey参数,并将该参数注入到模态框的HTML页面中:

export const openDialog = (itemKey) => {
  const html = HtmlService.createHtmlOutputFromFile('dialog')
    .setWidth(600)
    .setHeight(600)
    .setSandboxMode(HtmlService.SandboxMode.IFRAME);
  
  // 将key参数注入到模态框的全局作用域,用JSON.stringify避免XSS风险
  html.append(`<script>window.itemKey = ${JSON.stringify(itemKey)};</script>`);
  
  DocumentApp.getUi().showModalDialog(html, '编辑项目');
};

2. 在React侧边栏组件中调用服务器端函数并传参

在侧边栏的项目列表组件里,给每个项目的编辑按钮添加点击事件,通过google.script.run调用服务器端的openDialog并传递对应项目的key:

const ProjectItem = ({ item }) => {
  const handleEdit = () => {
    // 直接调用服务器端函数并传入当前项目的key
    google.script.run.openDialog(item.key);
  };

  return (
    <div style={{ padding: '8px', borderBottom: '1px solid #eee' }}>
      <span>{item.name}</span>
      <button onClick={handleEdit} style={{ marginLeft: '16px' }}>编辑</button>
    </div>
  );
};

3. 在模态框组件中获取key并加载对应数据

在模态框的React组件中,通过全局变量window.itemKey获取传递的参数,再根据key请求服务器端的项目详情数据:

import { useState, useEffect } from 'react';

const Dialog = () => {
  const [itemKey, setItemKey] = useState('');
  const [itemData, setItemData] = useState(null);

  useEffect(() => {
    // 获取传递的key
    setItemKey(window.itemKey);
    
    // 根据key请求服务器端的项目详情
    google.script.run
      .withSuccessHandler((data) => setItemData(data))
      .getItemDetails(itemKey);
  }, []);

  if (!itemData) return <div>加载中...</div>;

  return (
    <div style={{ padding: '16px' }}>
      <h2>编辑项目:{itemKey}</h2>
      <div>
        <label>项目名称:</label>
        <input type="text" value={itemData.name} onChange={(e) => {/* 处理输入变更 */}} />
      </div>
      {/* 其他编辑表单字段 */}
    </div>
  );
};

export default Dialog;

注意事项

  • 确保服务器端的openDialog和getItemDetails函数都已正确导出,并且在React-Google-Apps-Script的配置中被暴露给客户端
  • 传递参数时务必用JSON.stringify处理,避免特殊字符导致的语法错误或XSS风险

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 11:13:19