React Native getInitialState()语法错误(意外令牌)

时间:2017-07-05 12:20:13

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

我似乎无法弄清楚为什么这段代码会在第14行给出语法/意外令牌错误。任何帮助都将非常感激。

我很确定getInitialState()设置正确并且不确定它为什么会抛出错误。

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

export default class Test extends Component {
  getInitialState() {
    return {
      test: ''
    };
  },

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

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

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

1 个答案:

答案 0 :(得分:1)

您正在将ES5编写反应组件的方式与ES6(ES2015)编写反应组件的方式相结合。请在此处详细了解https://facebook.github.io/react/docs/react-without-es6.html

修复您的代码,修改如下

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

export default class Test extends Component {
  constructor(props) {
    super(props);
    this.state =  {
      test: ''
    };
  }

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

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

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