React Native使用另一个函数循环返回多个JSX组件

时间:2018-07-12 09:37:44

标签: javascript reactjs function react-native return

我想使用循环返回多个JSX组件(Foodcards)。我使用了另一个函数来返回循环内的组件。但是该函数未返回组件。食品卡是一个将名称和比率作为输入的组件。从Foodcards返回组件(renderMenu())时,代码工作正常。

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 {

    returnFoodCard(text1, text2) {
        return <Foodcards Name={text1} Rate={text2} />
    }

    renderMenu() {
        var fetchedJSON = this.props.dishes;
        var fetchedString = JSON.stringify(fetchedJSON);
        var i = 0;
        var arrayOfLines = fetchedString.split(",")
        for (i = 0; i < arrayOfLines.length; i++) {
            var arr = arrayOfLines[i].split('$');
            ToastAndroid.show(arr[1], ToastAndroid.SHORT);
            this.returnFoodCard(this, arr[1], arr[2]);
        }
    }    

    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"
    },

});

1 个答案:

答案 0 :(得分:1)

问题是您没有从renderMenu方法返回任何内容。

尝试这样的事情:

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('$');
        ToastAndroid.show(arr[1], ToastAndroid.SHORT);
        return this.returnFoodCard(arr[1], arr[2]);
    });
}

returnFoodCard似乎有两个参数,而您传入​​的是三个...