在react-native中创建和调用我自己的JavaScript库
问题描述:
我只想包含助手类中的一些JavaScript函数。例如,运行一些抓取或异步操作等。我不想创建一个Component类,而只是纯粹的JavaScript。我不认为我可以创建一个js文件,将代码放入并从Component中调用它。我需要注册吗?在react-native中创建和调用我自己的JavaScript库
答
是的,你可以通过模块导入。反应本机来与巴贝尔编译器包装。您可以在https://facebook.github.io/react-native/docs/javascript-environment.html处引用所有启用的语法转换器。
巴贝尔在模块https://babeljs.io/learn-es2015/#ecmascript-2015-features-modules上也有很好的解释。
例如:
文件helper.js
export function doSomething(){
console.log("I am calling module helper through exported function")
}
文件App.js
import {doSomething} from "./helper"; //simply imports function from another file.
import React, { Component } from "react";
import { AppRegistry, Text, View} from "react-native";
export default class ExampleComponent extends Component {
componentDidMount(){
doSomething(); //invoke your function here for example.
}
render() {
return (
<View>
<Text>I'm a text</Text>
</View>
)
}
}
AppRegistry.registerComponent("Example",() => ExampleComponent);
谢谢,这工作。我一直在浏览一些反应原生的教程,但他们还没有涉及到这个主题。我假设您可以轻松创建一个具有多个功能的ES6类,将其导出,然后将其导入到组件中。 –
我能够用我可以作为工具类引用的各种方法创建一个ES6类。现在我可以在多个组件中引用这些函数。 –
很高兴知道它帮助:) – Siwananda