微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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
  }
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。