简体   繁体   English

如何在React Native中从子组件回调到父组件

[英]How to get callback from child component to parent component in React Native

I have been working on react-native to get the callback from child to parent. 我一直在进行react-native以获得从子代到父代的回调。 Below is the code snippet of my implementation: 下面是我的实现的代码片段:

MainView.js MainView.js

import React, { Component } from 'react';
import {
    StyleSheet,
    View,
    Text,
    Image,
    TouchableHighlight,
    FlatList,
    Dimensions,
} from 'react-native';
import ListCell from './ListCell';
import {displayAlert} from './CustomAlert';
type Props =  {
};

let winSize = Dimensions.get('window');
export default class MainView extends Component<Props> {

_keyExtractor = (item, index) => { return(index.toString());};

  _renderItem = ({item, index}) => {
    return (<ListCell
    item={item}
    index={index}
    onPressItem={this._onPressItem}
    />);
  };
  _onPressItem = (item,index) => {
    console.log("Pressed row : "+index);
    displayAlert();
    // this.props.navigation.navigate('Detail',{item: item});
  };
    render() {
        return(
            <FlatList
        style={styles.flatListStyle}
        data={this.props.listing}
        keyExtractor={this._keyExtractor}
        renderItem={this._renderItem}
      />
        );
    }
}

The list Cell Component for FlatList is : FlatList的列表单元组件是:

ListCell.js ListCell.js

import React, {PureComponent} from 'react';
import {
    StyleSheet,
    TouchableHighlight,
    View,
    Image,
    Text,
} from 'react-native'


export default class ListCell extends PureComponent {
  _onPress() {
    this.props._onPressItem(this.props.item,this.props.index);
  }
  render() {
    const item = this.props.item;
    const price = item.price_formatted.split(' ')[0];
    return (
      <TouchableHighlight
      style={styles.listCellContainer}
      onPress={this._onPress}
      underlayColor='#dddddd'>
        <View >
          <View style={styles.rowContainer}>
            <Image style={styles.thumb} source={{uri:item.img_url}}/>
            <View style={styles.textContainer}>
              <Text style={styles.price}>{price}</Text>
              <Text style={styles.title}>{item.title}</Text>
            </View>
          </View>
        </View>
      </TouchableHighlight>
    );

  }
}

this code will work fine when declared in single file, but when seperated in two different file it gives an error stating this.props._onPressItem is undefined when tap on cell. 在单个文件中声明时,此代码可以正常工作,但在两个不同的文件中分隔时,它会显示错误,指出此this.props._onPressItem在点击单元格时未定义。

I have followed the following https://medium.com/@ruthmpardee/passing-data-between-react-components-103ad82ebd17 approach but didn't succeed on that either Any suggestions would be helpful. 我已遵循以下https://medium.com/@ruthmpardee/passing-data-between-react-components-103ad82ebd17方法,但均未成功,任何建议都无济于事。

Got a quick look on your code. 快速查看您的代码。 This is what I found. 这就是我发现的。

export default class ListCell extends PureComponent {
  _onPress() {
    this.props.onPressItem(this.props.item,this.props.index); //Change: passing prop onPressItem and calling _onPressItem
  }
  render() {
    const item = this.props.item;
    const price = item.price_formatted.split(' ')[0];
    return (
      <TouchableHighlight
      style={styles.listCellContainer}
      onPress={this._onPress} //Try: Also bind the event () => this._onPress()
      underlayColor='#dddddd'>
        <View >
          <View style={styles.rowContainer}>
            <Image style={styles.thumb} source={{uri:item.img_url}}/>
            <View style={styles.textContainer}>
              <Text style={styles.price}>{price}</Text>
              <Text style={styles.title}>{item.title}</Text>
            </View>
          </View>
        </View>
      </TouchableHighlight>
    );

  }
}

Your prop is called onPressItem without an underscore. 您的道具称为onPressItem,不带下划线。

    this.props.onPressItem(this.props.item, this.props.index);

...and you should pass the function itself to your components onPress method, not the return value. ...并且您应该将函数本身传递给组件的onPress方法,而不是返回值。 So do... 那也是

      onPress={() => this._onPress}

...instead of... ...代替...

      onPress={this._onPress}

you can use like this this code for you parent component 您可以像这样的代码为您的父组件使用

class ParentComponent extends Component {
    onPressButtonChildren(data){
      console.log(data)
      //press button chilldre  
    }
    render(){
      return(
        <ListChildren data={this.props.data} fnPressButton={this.onPressButtonChildren.bind(this)}/>
      )
    }
}

export default ParentComponent

this is code for your children component and handle press button 这是您的孩子组件和手柄按钮的代码

const ListChildren = (props) => {
  const {price, title, image} = props.item
  const onPress = () => props.fnPressButton(props.item)
  return (
    <TouchableHighlight
      style={styles.listCellContainer}
      onPress={onPress} //Try: Also bind the event () => this._onPress()
      underlayColor="#dddddd"
    >
      <View>
        <View style={styles.rowContainer}>
          <Image style={styles.thumb} source={{ uri: img_url }} />
          <View style={styles.textContainer}>
            <Text style={styles.price}>{price}</Text>
            <Text style={styles.title}>{title}</Text>
          </View>
        </View>
      </View>
    </TouchableHighlight>
  );
};

export default ListChildren

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React Native:如何从子组件中的父组件访问变量? - React Native: How to access a variable from parent component in child component? 如何在反应中从子组件获取数据到父组件? - how to get data from child component to parent component in react? 如何在React Native中从子组件更改父状态? - How to change parent's state from child component in react native? React Native中如何从子组件调用父函数并将子组件的参数传递给父组件? - How can calling parent function from child component and passing parameters from child component to parent component in React Native? 将 SetState 从父组件传递给 React Native 中的子组件 - Pass SetState from parent component to a child component in React Native 在本机反应中将数据从子组件传递到父组件? - Passing data from child component to parent component in react native? React Native - 从父组件重新渲染子组件 - React Native - rerender child component from parent component 在 React Native 中从子组件 TextInput 更新父组件状态 - Updating Parent component state from Child component TextInput in React Native 从父组件更新子组件道具反应原生 - Update child component props from Parent component react native React中的回调参数如何从子组件传递到父组件? - How is an argument for a callback in React being passed from the child component to the parent component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM