错误 TS2339:类型“导航器”上不存在属性“剪贴板”

Son*_*sen 6 typescript reactjs

我在我正在更新的项目中遇到此错误 - 他们想要将数据复制到剪贴板。自定义数据,我可以轻松地将它们组合在一起

错误 TS2339:类型“导航器”上不存在属性“剪贴板”

import * as React from 'react';
import Loading from './Loading';
import axios from 'axios';
import { AppConfig } from '../../Config';
import 'jquery-ui-bundle';
// import 'jquery-ui-bundle/jquery-ui.css';
import '../helpers/datepicker-skins/jquery-ui-1.10.1.css';
import '../helpers/datepicker-skins/cangas.datepicker.css';

class Log extends React.Component<any, any> {
    validationCheck(): any {}

    constructor(props: any) {
        super(props);
        this.state = { FaultyUnits: [], FaultyUnitsPackages: [] };
    }
...
    public CopyEmailAddresses(event: any): void {
        navigator.clipboard.writeText("this.state.textToCopy");  <---- error on this line
    }
Run Code Online (Sandbox Code Playgroud)

键入时,建议显示剪贴板和写入文本,但在保存/编译时它不接受它。

当在剪贴板上单击 F12(转到 Defenition)时,我得到 lib.dom.d.ts:

....
/** The state and the identity of the user agent. It allows scripts to query it and to register themselves to carry on some activities. */
interface Navigator extends NavigatorAutomationInformation, NavigatorConcurrentHardware, NavigatorContentUtils, NavigatorCookies, NavigatorID, NavigatorLanguage, NavigatorNetworkInformation, NavigatorOnLine, NavigatorPlugins, NavigatorStorage {
    /** Available only in secure contexts. */
    readonly clipboard: Clipboard;
    /** Available only in secure contexts. */
    readonly credentials: CredentialsContainer;
    readonly doNotTrack: string | null;
....
Run Code Online (Sandbox Code Playgroud)

当我导航到 Clipboard 类时,我看到了我所期望的 - 读取和写入函数。

这个问题我看了半天,没有什么想法。

你们有什么想法吗?

tsconfig.json:

{
  "compilerOptions": {
    "outDir": "build/dist",
    "module": "esnext",
    "target": "es5",
    "lib": ["es6", "dom"],
    "sourceMap": true,
    "allowJs": true,
    "jsx": "react",
    "moduleResolution": "node",
    "rootDir": "src",
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "noUnusedLocals": true
  },
  "include": [
    "./**/*"
  ],
  "exclude": [
    "node_modules",
    "build",
    "scripts",
    "acceptance-tests",
    "webpack",
    "jest",
    "src/setupTests.ts",
    "src/**/*.ts",
    "src/*.ts",
    "config"
  ]
}
Run Code Online (Sandbox Code Playgroud)

小智 12

你应该试试:

window.navigator['clipboard'].writeText("this.state.textToCopy");
Run Code Online (Sandbox Code Playgroud)

代替:

navigator.clipboard.writeText("this.state.textToCopy");
Run Code Online (Sandbox Code Playgroud)