javascript - onPress 错误 "is not a function"和 "is undefined"

标签 javascript ios reactjs react-native touchablehighlight

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

enter image description here

我收到这些错误:

enter image description here

这是我的 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);

非常感谢任何输入!

最佳答案

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

renderRow={this.renderRow.bind()}

当然应该是:

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

关于javascript - onPress 错误 "is not a function"和 "is undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44569977/

相关文章:

javascript - MongoClient 连接中的语法错误

javascript - Safari13 webdriverio点击问题

ios - Realm 不支持 NSDiacriticInsensitivePredicateOption

ios - 对于以编程方式创建其所有内容的 UITableViewCell,我应该使用哪些初始化程序/方法?

ios - [UITableViewCell menuImage]:无法识别的选择器已发送到实例0x10bb1e5e0

reactjs - react 路由器 : share state between Routes without Redux

javascript - 类型错误 : boolean is not a function

javascript - 使用discord.js 将机器人消息保存在变量中

node.js - 管道模块扫描所有不相关的文件

javascript - 容器、行、列 - 在 React-Bootstrap 中不起作用