【问题标题】:Passing string from native module to react native从本机模块传递字符串以响应本机
【发布时间】:2019-07-04 23:25:07
【问题描述】:

我为 android 创建了一个原生模块(使用 kotlin 语言)

class TestModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
    override fun getName(): String {
        return "TestModule"
    }

    @ReactMethod
    fun testing(): String{
        return "my modules"
    }

}

然后我在 ModulesPackages 中注册了这个模块,并按照https://facebook.github.io/react-native/docs/native-modules-android.html 的说明将其添加到 MainApplication.tk

在 App.js 中

import {NativeModules} from 'react-native'
const TestingModule = NativeModules.TestModule;
type Props = {};
export default class App extends Component<Props> {
  render() {

    alert(TestingModule.testing());

    return (
      <View style={styles.container}>
        <Text style={styles.instructions}> test</Text>
      </View>

    );
  }
}

运行此程序后,我希望收到带有文本“我的模块”的警报,但我收到了带有文本“未定义”的警报

我不知道我做错了什么。我运行 react-native run-android 时没有看到任何错误或抱怨。

任何建议我做错了什么?

【问题讨论】:

    标签: react-native react-native-android


    【解决方案1】:

    native 模块和 js 模块之间的通信,你应该调用回调,承诺或使用事件。在您的情况下,testing 函数可能会更改为

    import com.facebook.react.bridge.Callback;
    
    ...
    
    @ReactMethod
    fun testing(callback: Callback): Void{
        callback.invoke("my modules")
    }
    

    编辑

    在这种情况下,你应该在 js 文件中传递一个回调:

    testCallback = (name) => {
        console.log(name);
    }
    
    componentDidMount() {
        TestingModule.testing(this.testCallback);
    }
    

    【讨论】:

    • 它似乎不起作用。在不更改 app.js 的情况下,我收到错误“...得到 0 个参数,预期为 1”。如果我放了一个变量,所以我有 alert(TestingModule.testing(testing)) ,我收到错误 "The callback getCurrentAppState() exists in module AppState, but only one callback may be registered to an function in a native module" 。
    • 调用@Denvi 时必须将函数传递给该本地模块,我已为我的答案进行了编辑
    • 谢谢,这适用于控制台。但是无论如何我可以分配该回调,将“TestModule”字符串命名为要在UI上显示的变量吗?无论我做什么,我都可以在控制台上获得该值,但我不知道如何将它分配给一个变量以在 UI 上显示
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多