如何使用 office-js 创建确认对话框并做出反应



我想为我的办公室 excel 插件编写一个简单的确认模式,用 React 编写。

这是行不通的,因为 window.confirm 已被 officejs 禁止(参见此解释(。

onClick={() => { if (window.confirm('Are you sure you wish to delete this item?')) { this.handleClick(); } }}>

根据officeJS文档,我可以使用对话框api,但这些对话框不是模态,因此与我的用例不匹配:我希望用户在继续操作之前确认操作。

还有别的办法吗?

谢谢

有一个模态 Fabric React 对话框组件。从您对用例的描述来看,这可能是您正在寻找的。它的参考资料在这里:Fabric React 中的对话框组件。

你也可以使用我使用的对话框API。请确保将url添加到清单xml AppDomain 中。

使用对话框 API,您可以通过创建一个单独的 HTML 页面 ( dialog.html ( 来搭载现有的 react 渲染,该页面具有与您用于为任务窗格渲染 react 相同的 ID(例如 container (:

dialog.html

<!-- Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. -->
<!-- See LICENSE in the project root for license information -->
<!doctype html>
<html lang="en" data-framework="typescript">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <!-- Office JavaScript API -->
    <script type="text/javascript" src="https://appsforoffice.microsoft.com/lib/1.1/hosted/office.js"></script>
</head>
<body>
    <div id="container"></div>
</body>
</html>

然后在主App,tsx文件中,可以对该 URL 查询变量进行条件检查dialogID如果存在,则呈现对话框,否则,呈现主任务窗格:

export function App() {
    // requires react-router-dom
    const urlQueryParameters = new URLSearchParams(window.location.search);
    return (
        <>
            {/* I'm a dialog window */ urlQueryParameters.get("dialogID") != null && <React.Fragment>
                <DialogWindow dialogID={urlQueryParameters.get("dialogID")}/>
            </React.Fragment>}
            {/* I'm NOT a dialog window (I'm the main taskpane ui) */ urlQueryParameters.get("dialogID") == null &&
                <React.Fragment>
                    ...

然后,您可以使用(传递表示它是对话框的 URL 查询变量(创建对话框提示:

    ...
<button onClick={() => {
    Office.context.ui.displayDialogAsync("https://host:3000/dialog.html?dialogID=" + dialogID, {promptBeforeOpen: false, displayInIframe: true, width: 30, height: 60});
}}>Create a dialog window</button>
    ...

最新更新