【问题标题】:React Native call components in imports js导入js中的React Native调用组件
【发布时间】:2016-11-23 17:54:49
【问题描述】:

我有一个 import.js,我正在其中写入所有模块的路径。例如。 color.js 和 button.js 在 import.js 中被识别。然后我想在其他组件中调用我的导入。我可以在 main.js 中调用所有模块的导入。但是在 button.js 中,我不能调用 color.js 在import.js中导入其中一个js文件时,不能调用import.js中的任何js文件。它也给出了这个错误:

1.undefined 不是对象(评估“COLOR.BUTTONDARK”)

2.[fatal][tid:com.facebook.react.RCTExceptionsManagerQueue] 未处理的 JS 异常:未定义不是对象(正在评估 'COLOR.BUTTONDARK')

3.[error][tid:com.facebook.react.JavaScript] 模块 AppRegistry 不是 注册的可调用模块。

//import.js
module.exports = {
  BUTTON: require('./../components/XYZButton'),
  COLOR: require('./../styles/colors'),
};


//colors.js
module.exports = {
  BUTTONDARK: '#084C6E',
  TEXTLIGHT: '#FFFFFF'
  };


//xyzbutton.js
const COLOR = require('./../constants/imports');
class XYZButton extends React.Component {
  render() {
  return (
    <TouchableHighlight>
      <View style={{backgroundColor:COLOR.BUTTONDARK}}>
        <Text style={{color:COLOR.TEXTLIGHT}}>
          {'TEST'}
        </Text>
      </View>
    </TouchableHighlight>
  );
  }
}
module.exports = (XYZButton);


//main.js
const {BUTTON, COLOR} = require('./../../../../constants/imports');
class Main extends React.Component {
  render() {
    return (
    <View style={{backgroundColor:COLOR.BUTTONDARK}}>
      <BUTTON
        onPress = {() => {
          this._handleSelectModulPage()
        }}
        style = {{
        alignItems: 'center',
        justifyContent: 'center'
        }}
      />
    </View>
    );
  }
}
module.exports = (Main);

【问题讨论】:

    标签: import module path react-native components


    【解决方案1】:

    我认为你有一个循环依赖。您需要在完成导入其定义之前定义的内容。

    1. main.js 需要 imports.js
    2. imports.js 需要 XYZButton.js
    3. XYZButton.js 需要 imports.js,此时它还没有完成加载自己的依赖项。然后它会返回一个未定义的对象,这会导致您的 COLOR 常量出现错误。

    您真正想要做的是完全废弃imports.js,只需要其他文件的相对路径。拥有一个 imports.js 文件并没有真正给您带来任何好处。

    【讨论】:

    • 正是这个。如果 A 需要 B,B 需要 A,那么当 A 加载时,它会尝试加载 B,当 B 加载时,它将尝试加载 A,以此类推。
    猜你喜欢
    • 1970-01-01
    • 2019-06-21
    • 2023-01-10
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    相关资源
    最近更新 更多