我正在学习如何使用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,
},
});这就是我得到的错误。

发布于 2018-08-12 05:04:11
根据您显示的代码,这是因为您没有在App.js中正确导入模块,您应该在与App.js相同的目录中创建一个名为ToastExample.js的文件,然后将
import {NativeModules} from 'react-native';
module.exports = NativeModules.ToastExample;如果在您的ToastModule.java中有
@Override
public String getName() {
return "ToastExample";
}在getName()方法上。
https://stackoverflow.com/questions/51800550
复制相似问题