React-Native 回调函数/方法不起作用

React-Native Callback Function / Method does not work

我看了几个教程,但我不明白为什么传递回调函数和回调方法都不起作用。

当我console.log回调函数未定义时。

请帮忙。

import React, { Component } from 'react';
import { FlatList } from 'react-native';
import { RecipeCard } from '../RecipeCard/RecipeCard';
import recipeData from '../../config/SampleDataRecipeList.json';

class RecipeList extends Component {
  constructor(props) {
    super(props);
    this.handlePress = this.handlePress.bind(this);
  }
  state = {};

  handlePress() {
    console.log('Handle Press');
  }

  handleClick = () => {
    console.log('Handle Click');
  };

  renderItem({ item }) {
    return (
      <RecipeCard
        title={item.title}
        persons={item.persons}
        time={item.time}
        uri={item.uri}
        onPress={this.handlePress}
      />
    );
  }

  render() {
    return (
      <FlatList
        data={recipeData}
        renderItem={this.renderItem}
        keyExtractor={(item, index) => index.toString()}
      />
    );
  }
}

export { RecipeList };

解决方案是更改为在构造函数中绑定 renderItem 或将其更改为像

这样的粗箭头函数
renderItem = ( ) => {...}

我的建议是使用如下箭头函数:

  renderItem = item => {
    return (
      <RecipeCard
        title={item.title}
        persons={item.persons}
        time={item.time}
        uri={item.uri}
        onPress={this.handlePress}
      />
    );