代码之家  ›  专栏  ›  技术社区  ›  Defrian

React本机回调函数/方法不工作

  •  1
  • Defrian  · 技术社区  · 7 年前

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

    当我控制台。日志回调函数未定义。

    请帮忙。

    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 };
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Praveen George    7 年前

    我建议使用以下箭头函数:

      renderItem = item => {
        return (
          <RecipeCard
            title={item.title}
            persons={item.persons}
            time={item.time}
            uri={item.uri}
            onPress={this.handlePress}
          />
        );
    
        2
  •  0
  •   Defrian    7 年前

    解决方案是要么在构造函数中绑定renderItem,要么将其更改为胖箭头函数,如

    renderItem = ( ) => {...}