我正在开发一个应用程序,它充当 Xamarin 和 React Native 之间的bridge。我正在关注这个GitHub项目
https://github.com/voydz/xamarin-react-native
这是我的NativePackage.cs代码-
using Com.Facebook.React.Bridge;
using Com.Facebook.React.Uimanager;
using Com.Facebook.React;
using Java.Interop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Android.Widget;
using Android.Content;
namespace ReactNative.Droid
{
public class NativePackage : Java.Lang.Object, IReactPackage
{
public IList<INativeModule> CreateNativeModules(ReactApplicationContext context)
{
var module = new NativeModule(context);
var list = new List<INativeModule> { module };
Console.WriteLine("Hello CreateNativeModules");
return list;
}
public IList<ViewManager> CreateViewManagers(ReactApplicationContext context)
{
Console.WriteLine("Hello CreateViewManagers");
return new List<ViewManager> { };
}
}
public class NativeModule : ReactContextBaseJavaModule
{
public NativeModule(ReactApplicationContext reactContext) : base(reactContext)
{
Console.WriteLine("Hello NativeModule");
}
public override string Name => "XNativeModule";
[Export("Foo")]
[ReactMethod]
public void Foo()
{
Console.WriteLine("Hello Native World");
Toast.MakeText(ReactApplicationContext, "Hello Native World", ToastLength.Long).Show();
}
}
}
以下是我的index.js代码
import React, { Component } from 'react';
import {
AppRegistry,
Platform,
StyleSheet,
Text, Button,
View,NativeModules
} from 'react-native';
console.log(NativeModules);
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 this is part of React,\n' +
'Shake or press menu button for dev menu',
});
const {XNativeModule}=NativeModules;
const RNHelloWorld=()=> {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Hey there Judson! This is React native project
</Text>
<Text style={styles.instructions}>
To get started, edit App.js
</Text>
<Text style={styles.instructions}>
{instructions}
</Text>
<Button onPress={() => this.XNativeModule.Foo()} title="Call Native Module" />
</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,
},
});
// Module name
AppRegistry.registerComponent('MyReactNativeApp', () => RNHelloWorld);
单击按钮时出现以下错误。
undefined is not an object (evaluating 'u.Foo')
我不知道如何解决这个问题。有什么建议吗?
因为 Foo 不是一个类方法,你能从按钮按下中删除
this
吗?
<Button onPress={() => XNativeModule.Foo()} title="Call Native Module" />