Reactjs React本机回调函数/方法不起作用

Reactjs React本机回调函数/方法不起作用,reactjs,react-native,callback,react-native-ios,Reactjs,React Native,Callback,React Native Ios,我读了一些教程,但我不明白为什么传递回调函数和回调方法都不起作用 当I console.log时,回调函数未定义 请帮忙 import React, { Component } from 'react'; import { FlatList } from 'react-native'; import { RecipeCard } from '../RecipeCard/RecipeCard'; import recipeData from '../../config/SampleDataReci

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

当I 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 };
import React,{Component}来自'React';
从“react native”导入{FlatList};
从“../RecipeCard/RecipeCard”导入{RecipeCard};
从“../../config/SampleDataRecipeList.json”导入recipeData;
类RecipeList扩展了组件{
建造师(道具){
超级(道具);
this.handlePress=this.handlePress.bind(this);
}
状态={};
女佣(){
console.log('handlepress');
}
handleClick=()=>{
log('handleclick');
};
renderItem({item}){
返回(
);
}
render(){
返回(
index.toString()}
/>
);
}
}
导出{RecipeList};

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

renderItem = ( ) => {...}

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

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

Bind
renderItem
在你的constructor.works中。非常感谢。不用担心,我建议你使用箭头函数,这样你就不必一直绑定。要做到这一点,请将所有函数从
handlePress(){…}
更改为
handlePress=()=>{…}
argh。是的,您是对的。react native flatlist文档也可以做到这一点。非常感谢。谢谢。就这样