javascript - 在 react native 中将值从一个文件导入到另一个文件时出现问题

标签 javascript react-native import

我正在学习 ReactNative,现在我正在研究如何组织文件(现在我将为每个页面创建一个文件夹,每个文件夹都有一个索引、函数和样式文件)。但由于某种原因,我无法将信息导入 index.js,无法使用样式或函数,当我打开页面时,它不会返回 func 方法。

我想知道我是否使用了错误的导入。使用 import { MenuFunctions} from './Menu' 导致出现错误,表示未导入任何内容,此错误不再出现,但仍然没有返回任何内容。

这是我的代码,索引、菜单和样式都在同一个文件夹中。

index.js

import React from 'react';
import MenuFunctions from './Menu';
import MenuStyles from './styles'
import { Text, View } from 'react-native';

export default class MenuPage extends React.Component {
    render(){
        return(
            <View>
                <Text> Text: {MenuFunctions.func} </Text>
            </View>
        );
    }
}

Menu.js

import React from 'react';

export default class MenuFunctions extends React.Component{
    constructor(props){
        super(props);
    }

    func = () => {return "Hello, World!"};
}

styles.js

import React from 'react';
import { StyleSheet } from 'react-native';

export default class MenuStyles extends React.Component{
    styles = StyleSheet.create({
        text: {
            color: "red",
        }
    });
}

最佳答案

Menu.jsstyles.js 不应该是 React.Component 并且您忘记调用 Func 方法,缺少 ()

React.Component 是一个仅包含返回 JSX 元素的渲染方法的 UI 组件。

您的代码应如下所示:

index.js

import React from 'react';
import MenuFunctions from './Menu';
import MenuStyles from './styles';
import {Text, View} from 'react-native';

export default class MenuPage extends React.Component {
  render() {
    return (
      <View>
        <Text> Text: {MenuFunctions.func()} </Text>
      </View>
    );
  }
}

Menu.js

import React from 'react';

class MenuFunctions {
  func = () => {
    return 'Hello, World!';
  };
}

export default new MenuFunctions();

styles.js

import {StyleSheet} from 'react-native';

export default styles = StyleSheet.create({
  text: {
    color: Colors.red30,
  }
});

关于javascript - 在 react native 中将值从一个文件导入到另一个文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57463374/

相关文章:

javascript - 为什么嵌套的 for 循环没有完成?

javascript - 为具有可变内容的行内 block 元素提供相同的高度?

react-native - React Native Card 水平 ScrollView 和/或 FlatList

python - PyInstaller/Py2exe - 在单文件编译中包含带有第三方脚本的 os.system 调用

python - 在python中导入excel csv文件

javascript - 如何从鼠标指针创建 "aura"效果?

javascript - 在状态 `becameInvalid` 中尝试处理事件 'root.loaded.saved'

ios - 运行 pod install : Invalid attribute name 时出错

javascript - react native : How to add variables inside View?

java - 从空包中导入所有内容