如何在 React JSX 中调用 Web API? [英] How can I call Web APIs in React JSX?

查看:32
本文介绍了如何在 React JSX 中调用 Web API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 React 和 Electron 编写音乐播放器,并希望为音频添加元数据,以便获得 MPRIS 支持.所以我做了一些搜索,发现 Media Session API 是什么我需要.为了测试它,我将上述链接包含的示例代码中的代码复制到我项目中的一个函数中.

I'm writing a music player with React and Electron and want to add metadata for the audio so as I can get MPRIS support. So I did some searching and found Media Session API is what I needed. To test it, I copied the code from the exmaple code contained by the above link into a function in my project.

  navigator.mediaSession.metadata = new MediaMetadata({
    title: 'Unforgettable',
    artist: 'Nat King Cole',
    album: 'The Ultimate Collection (Remastered)',
    artwork: [
      { src: 'https://dummyimage.com/96x96',   sizes: '96x96',   type: 'image/png' },
      { src: 'https://dummyimage.com/128x128', sizes: '128x128', type: 'image/png' },
      { src: 'https://dummyimage.com/192x192', sizes: '192x192', type: 'image/png' },
      { src: 'https://dummyimage.com/256x256', sizes: '256x256', type: 'image/png' },
      { src: 'https://dummyimage.com/384x384', sizes: '384x384', type: 'image/png' },
      { src: 'https://dummyimage.com/512x512', sizes: '512x512', type: 'image/png' },
    ]
  });

我把它放到一个函数中,当播放下一首歌曲时,组件会调用该函数.但是,我得到了这样的错误:

I put it into a function that a component will call when the next song is played.However, I got errors like this:

Failed to compile.

./src/components/FM/Cover/index.jsx
  Line 112:  'MediaMetadata' is not defined  no-undef

Search for the keywords to learn more about each error.

为什么?

推荐答案

您需要引用 window 对象.

window.MediaMetadata
^^^^^^

这是因为 babel/es-lint 不知道 MediaMetadata 存在并且会抛出错误.由于 Chrome 将此对象作为全局变量注入,因此可以通过 window 对象访问它.

This is because babel/es-lint does not know MediaMetadata exists and will throw an error. Since Chrome injects this object as a global variable, it is accessible via the window object.

(为了便于使用,重新发布@AngelSalazar 在 OP 的评论中所说的内容)

(re-posting what @AngelSalazar said in the comments of the OP for ease of use)

这篇关于如何在 React JSX 中调用 Web API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆