React - 意外令牌,预期;

新手上路,请多包涵

抛出的错误是:Unexpected token, expected; (9:16) 这指向 renderNumbers() 函数的第一行。我的语法有什么问题?我对这里需要改变什么以使其工作感到有点困惑。

 import React, { PropTypes } from 'react';
import {
  StyleSheet,
  View,
  Text,
  TouchableOpacity
} from 'react-native';

renderNumbers() {
  return this.props.numbers.map(n =>
    <Text>{n}</Text>
  );
}

export default class Counter extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.appName}>
          Countly
        </Text>
        <Text style={styles.tally}>
          Tally: {this.props.count}
        </Text>
        <Text style={styles.tally}>
          Numbers: {this.props.numbers}
        </Text>
        <View>
          {this.renderNumbers()}
        </View>
        <TouchableOpacity onPress={this.props.increment} style={styles.button}>
          <Text style={styles.buttonText}>
            +
          </Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={this.props.decrement} style={styles.button}>
          <Text style={styles.buttonText}>
            -
          </Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={this.props.power} style={styles.button}>
          <Text style={styles.buttonText}>
            pow
          </Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={this.props.zero} style={styles.button}>
          <Text style={styles.buttonText}>
            0
          </Text>
        </TouchableOpacity>
      </View>
    );
  }
}

Counter.propTypes = {
  count: PropTypes.number,
  numbers: PropTypes.func,
  increment: PropTypes.func,
  decrement: PropTypes.func,
  zero: PropTypes.func,
  power: PropTypes.func
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF'
  },
  appName: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10
  },
  tally: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 20,
    fontSize: 25
  },
  button: {
    backgroundColor: 'blue',
    width: 100,
    marginBottom: 20,
    padding: 20
  },
  buttonText: {
    color: 'white',
    textAlign: 'center',
    fontSize: 20
  }
});

谢谢您的帮助。

原文由 Wasteland 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 352
1 个回答

你不应该使用 function renderNumbers() 吗?看起来 renderNumbers 不是 Counter 类的方法,而是代码中的一个单独的函数。

顺便说一句, renderNumbers 被定义了两次,尽管它是合法的,而不是问题的原因。

编辑:

如果你想声明 renderNumbers() 作为类的 原型方法 Counter ,在类中定义它:

 export default class Counter extends React.Component {

    renderNumbers() {
       ...
    }

    ...

}

否则,使用关键字 function 来定义一个 函数

 function renderNumbers() {
    ...
}

这只是 ES6 的语法。

原文由 Philip Tzou 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进