【问题标题】:React Native getInitialState() syntax error (unexpected token)React Native getInitialState() 语法错误(意外令牌)
【发布时间】:2017-07-05 12:20:12
【问题描述】:

我似乎无法弄清楚为什么此代码在第 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);

【问题讨论】:

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


    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 2017-07-28
      • 1970-01-01
      • 2018-01-25
      • 1970-01-01
      • 1970-01-01
      • 2017-08-09
      • 2016-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多