2

我正在尝试NDEFReader()在 React 中用于 NFC 扫描/写入。此功能适用于 Chrome 81(您可以通过以下链接在您的手机上试用 Chrome Beta 版)。

GoogleChromeNfcSample , WhatWebCanDoTodayNfc

要启用此功能,您需要进入chrome://flags/并启用Experimental Web Platform features

问题是我无法在 React 中完成这项工作。我将 create-react-app 与 TypeScript 和控制台输出一起使用:

找不到名称“NDEFReader”

我认为这会导致 webpack 检查。我已经尝试更改 tsconfig.json 中的一些设置,但没有任何效果。有谁知道,如何启用实验性 js/ts 编译以启用此功能?

4

2 回答 2

3

Web NFC 人员在https://github.com/w3c/web-nfc/blob/gh-pages/web-nfc.d.ts提供 TypeScript 定义

// Type definitions for Web NFC
// Project: https://github.com/w3c/web-nfc
// Definitions by: Takefumi Yoshii <https://github.com/takefumi-yoshii>
// TypeScript Version: 3.9

// This type definitions referenced to WebIDL.
// https://w3c.github.io/web-nfc/#actual-idl-index

interface Window {
  NDEFMessage: NDEFMessage
}
declare class NDEFMessage {
  constructor(messageInit: NDEFMessageInit)
  records: ReadonlyArray<NDEFRecord>
}
declare interface NDEFMessageInit {
  records: NDEFRecordInit[]
}

declare type NDEFRecordDataSource = string | BufferSource | NDEFMessageInit

interface Window {
  NDEFRecord: NDEFRecord
}
declare class NDEFRecord {
  constructor(recordInit: NDEFRecordInit)
  readonly recordType: string
  readonly mediaType?: string
  readonly id?: string
  readonly data?: DataView
  readonly encoding?: string
  readonly lang?: string
  toRecords?: () => NDEFRecord[]
}
declare interface NDEFRecordInit {
  recordType: string
  mediaType?: string
  id?: string
  encoding?: string
  lang?: string
  data?: NDEFRecordDataSource
}

declare type NDEFMessageSource = string | BufferSource | NDEFMessageInit

interface Window {
  NDEFReader: NDEFReader
}
declare class NDEFReader extends EventTarget {
  constructor()
  onreading: (this: this, event: NDEFReadingEvent) => any
  onreadingerror: (this: this, error: Event) => any
  scan: (options?: NDEFScanOptions) => Promise<void>
  write: (
    message: NDEFMessageSource,
    options?: NDEFWriteOptions
  ) => Promise<void>
}

interface Window {
  NDEFReadingEvent: NDEFReadingEvent
}
declare class NDEFReadingEvent extends Event {
  constructor(type: string, readingEventInitDict: NDEFReadingEventInit)
  serialNumber: string
  message: NDEFMessage
}
interface NDEFReadingEventInit extends EventInit {
  serialNumber?: string
  message: NDEFMessageInit
}

interface NDEFWriteOptions {
  overwrite?: boolean
  signal?: AbortSignal
}
interface NDEFScanOptions {
  signal: AbortSignal
}
于 2020-12-15T11:40:30.070 回答
1

这与 Webpack 检查或您的 tsconfig 或“实验性 JavaScript”无关。

只是没有NDEFReader()可用的类型,所以 TypeScript 认为你有错字。

您可以在源代码树中NDEFReader使用类似文件extra-globals.d.ts(名称无关紧要,只要它是 a )在类型中存根。.d.ts这基本上告诉 TypeScript 全局 Window 接口有一个额外的字段,NDEFReader,你真的不知道它的类型:

declare global {
  interface Window {
    NDEFReader: any;
  }
}

export {};
于 2020-03-09T08:34:32.273 回答