React Native给出错误,变量未定义

问题描述

我已经使用require()链接一个外部JS文件,它甚至可以识别它。当我从该外部文件调用函数时,它将指示该函数已被识别,但仍会给出无法找到变量的错误(在我的情况下是名为text()的函数)。 我的App.js:

require('./comp/functions.js')
import React from 'react'
import {View,Text,StyleSheet,Button} from 'react-native'


export default function App() {
      return(<>
      <View style={styles.loginBox}>
        <Text style={{textAlign: "center",fontWeight: "bold",fontSize: 30}}>LOGIN</Text>
        <Button title="Login Now!" onPress={test}/>

      </View>
      </>)
}

const styles = StyleSheet.create({
   loginBox: {
     position: "relative",top: 100
   }
})

functions.js:

function test() {
    alert(123)
  }

我希望它在立即登录时运行test()函数!按钮被按下

解决方法

首先需要从functions.js导出函数。然后,您可以import将其插入您的应用程序。以下应该起作用。

functions.js

export default function test() {
  alert(123);
}

app.js

import test from "./functions";
import React from "react";
import { View,Text,StyleSheet,Button } from "react-native";

export default function App() {
  return (
    <>
      <View style={styles.loginbox}>
        <Text style={{ textAlign: "center",fontWeight: "bold",fontSize: 30 }}>
          LOGIN
        </Text>
        <Button title="Login Now!" onPress={test} />
      </View>
    </>
  );
}

const styles = StyleSheet.create({
  loginbox: {
    position: "relative",top: 100
  }
});