React Native无index.js文件,如何注册TrackPlayer.registerPlaybackService?
React Native无index.js时注册TrackPlayer播放服务的解决方案
一、添加index.js并修改entryPoint的方案完全可行
这是社区和官方默认推荐的做法,具体操作步骤如下:
- 在项目根目录新建
index.js文件,写入以下代码(注意替换播放服务文件路径):
import { AppRegistry } from 'react-native'; import TrackPlayer from 'react-native-track-player'; import App from './App'; import { name as appName } from './app.json'; // 注册播放服务,指向你的播放逻辑文件 TrackPlayer.registerPlaybackService(() => require('./playback-service')); // 注册主应用组件 AppRegistry.registerComponent(appName, () => App);
- 修改项目入口配置:
- Android:打开
android/app/build.gradle,找到project.ext.react配置块,将entryPoint的值改为"index.js" - iOS:打开
ios/[你的项目名]/AppDelegate.m,把jsBundleURLForBundleRoot的参数从@"App"改成@"index"
- Android:打开
- 确保
playback-service.js文件存在,里面实现播放相关的事件逻辑(比如播放、暂停、进度更新等),这个文件必须独立,不能和主组件代码混写。
二、无需新建index.js的替代方案
如果不想新增index.js,也可以直接在App.js里调整代码顺序,提前注册播放服务:
import { AppRegistry } from 'react-native'; import TrackPlayer from 'react-native-track-player'; import { name as appName } from './app.json'; // 必须在注册主组件前调用播放服务注册 TrackPlayer.registerPlaybackService(() => require('./playback-service')); const App = () => { // 你的App组件原有代码 }; // 注册主组件 AppRegistry.registerComponent(appName, () => App); export default App;
不过这种方式存在小瑕疵:开启热重载时可能会触发重复注册的警告,因为App组件会被重新渲染,而播放服务注册应该只执行一次。所以如果追求稳定性,还是优先选择新增index.js的方案。
内容的提问来源于stack exchange,提问作者Nam Dang
相关产品推荐
相关产品推荐

