android - React-Native Native Android 模块 - Toast 示例
问题描述
我正在尝试学习使用 android 本机模块并使用 react-native 文档中的 toast 示例。(https://facebook.github.io/react-native/docs/native-modules-android)。但是,我面临一个问题,即我试图导出的本机模块无法解析/取消定义。
我的目录结构如下:
example
-android
-app
-src
-main
- java
-com
-example
-CustomToastPackage.java
-ToastModule.java
-MainActivity.java
-MainApplication.java
- res
- AndroidManifest.xml
-ios
-app.js
-index.js
-package.json
我的 index.js:
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import {NativeModules} from 'react-native';//Added this
module.exports = NativeModules.ToastAndroidTutorial;//Added this
AppRegistry.registerComponent(appName, () => App);
还有我的 App.js
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import ToastExample from './ToastExample';//Added this
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
android:
'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});
type Props = {};
export default class App extends Component<Props> {
render() {
return (
<View style={styles.container}>
ToastExample.show('Awesome', ToastExample.SHORT);//Added this
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.instructions}>To get started, edit App.js</Text>
<Text style={styles.instructions}>{instructions}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
这是我得到的错误。
解决方案
根据您显示的代码,这是因为您没有正确导入模块,您应该在同一目录中App.js
创建一个名为的文件,然后放置ToastExample.js
App.js
import {NativeModules} from 'react-native';
module.exports = NativeModules.ToastExample;
如果ToastModule.java
你有
@Override
public String getName() {
return "ToastExample";
}
在getName()
方法上。
推荐阅读
- c# - 单元测试 .NET Core 3 Web API 控制器
- javascript - 如何使用 Firebase 功能删除其他用户?
- linq - 在选择许多数据 IQueryable Vs For 循环(使用实体框架)时,哪种方式可以获得高性能
- vue.js - 第一次点击搜索时表格组件未更新
- json - 如何从 json 文件动态填充 ansible 角色的参数?
- git - 克隆裸 git 存储库并在其他位置跟踪文件
- c# - 有没有办法改变 NonClientFrameEdges 的颜色或使它们不可见(尤其是 WPF/.NET)?
- scala - janus websocket 服务器返回 403 通过 docker 运行
- data-structures - Julia中的不相交集数据结构
- typescript - 在 `d.ts` 文件中使用 `export` 有意义吗?