React native:组件未定义?无法导入?

时间:2017-07-13 19:54:54

标签: javascript reactjs react-native react-native-ios

好的,非常新的在这里做出反应,我试图非常简单地导入另一个.js文件并让它在index.ios.js中的主render() func中运行

我到处寻找并尝试了import and require这样做,但是我遇到了错误:

Component is not defined

这就是我所拥有的,只是添加了导入行就会引发错误:

import React, { Component } from 'react';
import { Button, Card } from 'react-native-material-design';
import {
  StyleSheet,
  Text,
  View,
  Animated,
  Easing,
  ScrollView,
  RefreshControl,
  AppRegistry
} from 'react-native';
//import { Container, Content } from 'native-base';

import TestClass from "./TestClass";
//var animation = require('./TestClass');

//BODY
export default class SkysReact extends Component {


  render() {
    return (<View style={styles.container}>
    <TestClass/>
    </View>);

    // return (<View style={styles.container}>
    // {this.test()}
    // </View>);
  }
  test() {
  console.log("Hello World")
}

animate()
{
  console.log("animate");
}
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#404040',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
    color: '#333333'
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('SkysReact', () => SkysReact);

我的另一堂课:

import React from 'react';
import Animation from 'lottie-react-native';
import {
  StyleSheet,
  Text,
  View,
  Animated,
  Easing,
  ScrollView,
  RefreshControl,
  AppRegistry
} from 'react-native';

export default class TestClass extends Component { // not defined error here

    render() {
      return (<View style={styles.container}>
      {this.test()}
      </View>);
    }
    test() {
    console.log("Hello World 2222")
  }
}
module.exports = TestClass;

如何在index.ios.js中显示TestClass?有什么问题?

2 个答案:

答案 0 :(得分:8)

啊,哈哈。我确切地知道它是什么。将TestClass文件的最顶行与我的下面进行比较。你会看到差异。解决这个问题,并完成你的工作。

import React, {Component} from 'react';
import Animation from 'lottie-react-native';
import {
  StyleSheet,
  Text,
  View,
  Animated,
  Easing,
  ScrollView,
  RefreshControl,
  AppRegistry
} from 'react-native';
export default class TestClass extends Component {

    render() {
      return (<View style={styles.container}>
      {this.test()}
      </View>);
    }
    test() {
    console.log("Hello World 2222")
  }
} 

您错过了import语句中的{Component}。我也拿了你的module.exports语句,这是不必要的。

答案 1 :(得分:-1)

this.test()不是<View>TestClass的有效子项,因为它不是有效的React组件,也不会返回。{/ p>

如果您想“测试”您的TestClass.render()功能正在运行,请将console.log()置于return语句之上,如下所示:

render() {
  this.test();
  return (
    <View style={styles.container}></View>
  );
}

当然,你实际上不会看到,因为TestClass没有任何孩子。

相关问题