【问题标题】:onPress error "is not a function" and "is undefined"onPress 错误“不是函数”和“未定义”
【发布时间】:2017-06-15 14:20:36
【问题描述】:

迈出我学习 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);

非常感谢您的任何意见!

【问题讨论】:

标签: javascript ios reactjs react-native touchablehighlight


【解决方案1】:

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

renderRow={this.renderRow.bind()}

当然应该是:

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

【讨论】:

    【解决方案2】:

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

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

    1. 删除this._onPress = this._onPress.bind(this);
    2. _onPress 重写为_onPress = user =&gt; console.log(user);
    3. 拨打电话&lt;TouchableHighlight onPress={() =&gt; this._onPress(user)}&gt;

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

    【讨论】:

    • 感谢您的回答!但是当我执行上述所有步骤时,我得到了 syntaxError Unexpected Token .. @Anduru
    • @fransBernhard 抱歉,在第 2 步中删除 const。更正了我的答案。
    • 仍然是同样的错误“_this2._onPress 不是一个函数。(在 '_this2._onPress(user', '_this2._onPress' 未定义”:( @Andru
    • 奇怪..您是否尝试过我发布的链接中的 RN 操场示例作为对您上面问题的评论?没有抛出这样的错误。所以也许尝试重新启动你的打包程序。不知道发生了什么..
    • 我现在在那个操场上玩耍,发现了错误。典型的初学者愚蠢的错误(..) - 但我会学习!
    猜你喜欢
    • 2017-12-06
    • 2014-08-03
    • 2020-11-07
    • 2015-02-24
    • 1970-01-01
    • 2013-06-21
    • 2017-03-20
    • 2013-06-06
    • 2014-05-26
    相关资源
    最近更新 更多