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

时间:2019-02-15 10:53:35

标签: javascript react-native callback react-native-flatlist react-native-component

我一直在React-native上进行工作,以使回调从子级传递到父级。下面是我的实现的代码片段:

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}
      />
        );
    }
}

FlatList的列表单元格组件为:

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.props._onPressItem未定义。

我已遵循以下https://medium.com/@ruthmpardee/passing-data-between-react-components-103ad82ebd17方法,但没有成功 任何建议都会有所帮助。

3 个答案:

答案 0 :(得分:2)

快速浏览一下您的代码。这是我发现的。

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>
    );

  }
}

答案 1 :(得分:1)

您的道具称为onPressItem,没有下划线。

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

...,您应该将函数本身传递给组件的onPress方法,而不是返回值。也是...

      onPress={() => this._onPress}

...而不是...

      onPress={this._onPress}

答案 2 :(得分:1)

您可以像这样使用 此代码为您的父组件

let request;
if ((<any>window).XMLHttpRequest) {
    request = new XMLHttpRequest;
    request.open('GET', 'http://www.mozilla.org', true);
} else if ((<any>window).ActiveXObject) {
    request = new ActiveXObject('Microsoft.XMLHttp');
}

if (request) {
    console.log('rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr', request);

    request.open('GET', 'https://www.google.com');
    if (request.status === 200) {
        console.log('Valid Url');
    } else {
        console.log('Invalid Url');
    }
}

这是您的孩子组件和手柄按钮的代码

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