反应从子组件到父组件的本机传递数据

时间:2018-07-13 18:07:26

标签: javascript android reactjs react-native

我试图使用callbackFromParent将对象从子组件传递到其父组件。但是代码遇到TypeError:undefined is not a function (evaluating '_this.state.foodBasket.push(dataFromChild)')。我不知道是什么导致此错误。我会同时附加父级组件和子级组件的源代码。

父母-Foodview.js

import React, { Component } from 'react'
import Dimensions from 'Dimensions'
import { Actions, ActionConst } from 'react-native-router-flux'
import * as firebase from 'firebase'


import GLOBALS from '../global/Globals';
import Background from '../Background.js';
import Foodcards from '../Foodcards.js';

const DEVICE_WIDTH = Dimensions.get('window').width;

import {
    StyleSheet,
    View,
    Text,
    TouchableOpacity,
    ScrollView,
    TextInput,
    ToastAndroid,
} from 'react-native'

export default class Foodview extends Component {

    myCallback = (dataFromChild) => {
        this.state.foodBasket.push(dataFromChild);
        this.setState({ foodBasket: this.state.foodBasket });
    }

    returnFoodCard(text1, text2, text3) {
        return <Foodcards itemID = {text3.trim()}  Name={text1.trim()} Rate={text2.trim()} callbackFromParent={this.myCallback} />
        
    }

    renderMenu() {
        var fetchedJSON = this.props.dishes;
        var fetchedString = JSON.stringify(fetchedJSON);
        var i = 0;
        var arrayOfLines = fetchedString.split(",")
        return arrayOfLines.map((line) => {
            var arr = line.split('$');
            return this.returnFoodCard(arr[1].replace(/"/g, '').replace(/}/g, ''), arr[2].replace(/"/g, '').replace(/}/g, ''), arr[0]);
        });
    }    

    constructor(props) {
        super(props);
        this.state = {
            foodBasket: {},
        }
    }

    render() {


        return (


            <View style={styles.Container}>

                {this.renderMenu()}

            </View>

        );
    }
}


const styles = StyleSheet.create({

    Container: {
        top: 5,
        flex: 1,
        backgroundColor: "white",
    },

    btnStyle: {
        backgroundColor: GLOBALS.linkTextColor,
        alignItems: 'center',
        top: 400,
        left: DEVICE_WIDTH / 2 - ((DEVICE_WIDTH - 250) / 2),
        paddingLeft: 8,
        width: DEVICE_WIDTH - 250,
        height: 30,
    },

    btnText: {
        left: -5,
        top: 5,
        color: "white"
    },

});

儿童-Foodcard.js

import React, { Component } from 'react';
import Dimensions from 'Dimensions';



import {
    View,
    Text,
    StyleSheet,
    TouchableOpacity,
    TextInput,
    Image,
} from 'react-native'


import GLOBALS from './global/Globals';


export default class Foodcards extends Component {

    constructor(props) {
        super(props);

        this.state = {
            quantity: 0,
        }
    }

    onPressPlus(text1, text2, text3) {
        var orderData = {
            foodItemID: text1,
            foodItemName: text2,
            foodItemPrice: text3
        }
        this.props.callbackFromParent(orderData);
    }

    render() {
        return (
            <View style={styles.Container}>
                <View style={styles.buttonContainer}>
                    <View style={{ flexDirection: 'row' }}>
                        <Text style={styles.textStyle} >{this.props.Name}</Text>
                        <Text style={styles.rateStyle} >{this.props.Rate}</Text>
                    </View>
                    <View style={{ flexDirection: 'row' }}>
                        <TouchableOpacity  style={styles.touchableContainer} >
                            <Image
                                source={require('../image/minus.png')}
                                style={styles.quantityMinusImageStyle} />
                        </TouchableOpacity>

                        <TextInput
                            style={styles.textStylePlaceholder}
                            placeholder=' 0'
                            returnKeyType={'done'}
                            onChangeText={(text) => this.setState({ quantity: text })}
                        />

                        <TouchableOpacity style={styles.touchableContainer} >
                            <Image
                                source={require('../image/plus.png')}
                                style={styles.quantityPlusImageStyle} />
                                onPressFunction={this.onPressPlus(this.props.itemID, this.props.Name, this.props.Rate)}
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        );
    }
}

const DEVICE_WIDTH = Dimensions.get('window').width;
const DEVICE_HEIGHT = Dimensions.get('window').height;

const styles = StyleSheet.create({
    Container: {
        top: 5,
        flex: 1,
        backgroundColor: "white",
    },
    touchableContainer: {
        width: DEVICE_WIDTH,
        alignItems: 'center',
    },
    textStyle: {
        left: 10,
        color: 'white',
        fontSize: 24,
    },
    rateStyle: {
        top: 4,
        left: 50,
        color: 'white',
        fontSize: 16,
    },
    textStylePlaceholder: {
        color: 'white',
        fontSize: 24,
        justifyContent: 'center',
    },
    buttonContainer: {
        top: 15,
        padding: 5,
        borderRadius: 10,
        backgroundColor: 'orange',
        alignItems: 'center',
    },
    textStyle: {
        color: 'white',
        fontSize: 24,
    },
    quantityMinusImageStyle: {
        left: 120,
        resizeMode: 'contain',
        width: 45,
        height: 45,
    },
    quantityPlusImageStyle: {
        left: -110,
        top: 2,
        resizeMode: 'contain',
        width: 40,
        height: 40,
    },
})

1 个答案:

答案 0 :(得分:1)

<TouchableOpacity style={styles.touchableContainer} >
      <Image
         source={require('../image/plus.png')}
         style={styles.quantityPlusImageStyle} />
          onPressFunction={this.onPressPlus(this.props.itemID, this.props.Name, this.props.Rate)}
</TouchableOpacity>

请将以上内容更改为:

<TouchableOpacity style={styles.touchableContainer} onPress=()=>{
                          this.onPressPlus(this.props.itemID, this.props.Name, this.props.Rate) }>
      <Image
        source={require('../image/plus.png')}
        style={styles.quantityPlusImageStyle} />

</TouchableOpacity>

您具有Touchable组件,该组件用于使其子级可点击并且功能名称为onPress您可以找到有关Touchable的更多详细信息 here