3

迈出我学习 Rect Native 的第一步,并被这些错误困扰了一段时间。当我单击项目时:

在此处输入图像描述

我收到这些错误:

在此处输入图像描述

这是我的 React Native 代码:

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

export default class Component5 extends Component {
  constructor(){
    super();
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      userDataSource: ds
    };
    this._onPress = this._onPress.bind(this);
  }

  _onPress(user){
    console.log(user);
  }

  renderRow(user, sectionId, rowId, hightlightRow){
    return(
      <TouchableHighlight onPress={() => {this._onPress(user)}}>
        <View style={styles.row}>
          <Text style={styles.rowText}>{user.name}: {user.email}</Text>
        </View>
      </TouchableHighlight>
    )
  }

  fetchUsers(){
    fetch('https://jsonplaceholder.typicode.com/users')
      .then((response) => response.json())
      .then((response) => {
        this.setState({
          userDataSource: this.state.userDataSource.cloneWithRows(response)
        });
      });
  }

  componentDidMount(){
    this.fetchUsers();
  }

  render() {
    return (
      <ListView
        style={styles.listView}
        dataSource={this.state.userDataSource}
        renderRow={this.renderRow.bind()}
      />
    );
  }
}

const styles = StyleSheet.create({
  listView: {
    marginTop: 40
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'center',
    padding: 10,
    backgroundColor: 'blue',
    marginBottom: 3
  },
  rowText: {
    flex: 1,
    color: 'white'
  }
})

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

非常感谢任何输入!

4

2 回答 2

3

菜鸟错误 - 忘记在组件中正确绑定 renderRow。我写:

renderRow={this.renderRow.bind()}

它当然应该是:

renderRow={this.renderRow.bind(this)}

于 2017-06-15T15:02:51.377 回答
1

您正在尝试this在许多不同的地方进行绑定,但例如在renderRow={this.renderRow.bind()}什么都不绑定。您有时还使用箭头函数语法..

我建议您对类方法使用箭头函数语法,这样您就不必再绑定this了(这是箭头样式函数语法的一个特性),即

  1. 删除this._onPress = this._onPress.bind(this);
  2. 重写_onPress_onPress = user => console.log(user);
  3. 通过调用它<TouchableHighlight onPress={() => this._onPress(user)}>

您可以使用所有其他类方法来执行此操作,而不必.bind(this)再次使用。

于 2017-06-15T14:31:28.643 回答