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

时间:2018-03-06 10:30:03

标签: reactjs react-native callback react-native-ios

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

当我在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 };

2 个答案:

答案 0 :(得分:1)

我建议使用像bellow这样的箭头函数:

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

答案 1 :(得分:0)

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

renderItem = ( ) => {...}