javascript - 无法在 React Native 中使用 switch 语句呈现任何内容

标签 javascript react-native

在 React Native 中使用 switch 语句时,我无法呈现任何内容。

我得到的只是一个空白屏幕,而不是文本输入或选择器元素。 我能够访问整个代码中完成的所有控制台日志。所以代码确实到达了案例。

import React, { Component } from 'react';
import { Text, View, TextInput, Picker } from 'react-native';
import data from '../Data.json';


class DynamicElement extends Component {

    renderElements() {
        const elements = [ ...data];
        elements.map(item => {
            console.log(item.elementType);
            console.log(typeof(item.elementType));
            switch(item.elementType) {
                case "text":
                    console.log("text reached here");
                    return (
                        <View style={{flex: 1}}>
                        <TextInput
                        style={styles.textInputStyle}
                        />
                        </View>
                    );

                case "select":
                    console.log("picker reached here")
                    return (
                        <View style={{flex:1}}> 
                        <Picker 
                        style={styles.selectInputStyle}
                        />
                        </View>
                    );

                default:
                    console.log("test reached here");
                    return <Text>Doesn't work</Text>
            }
        });
    }

    render() {
        return(
            <View style={{flex:1}}>    
                {this.renderElements()}
            </View>
        );
    }
}

const styles = {
    textInputStyle: {
        height: 40,
        width: '90%',
        textAlign: 'center',
        borderWidth: 1,
        borderColor: '#028b53',
        borderRadius: 8,
        marginBottom: 15
    },
    selectInputStyle: {
        flex: 1,
        height: 40,
        width: 100
    }
}

export default DynamicElement;

最佳答案

renderElements 应该返回组件数组

.....
return elements.map(item => {
    .....
    return <Component..
    .....
})

Javascript 函数默认返回 undefined 和。 React 不会为 undefined 渲染任何东西。 check here

关于javascript - 无法在 React Native 中使用 switch 语句呈现任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54480192/

相关文章:

javascript - 如何获取按钮标签的子标签值

javascript - jPlayer - 如何确定它是否正在播放

amazon-web-services - 全局二级索引上的 AppSync 查询

javascript - 无法在 angularjs 中的 http 响应回调函数之外访问 $scope 对象

javascript - Jquery 无法识别菜单包括

javascript - react : order of execution

javascript - 使 mobx 数据存储在应用程序重新启动时持久化( react native )

react-native - 无法弹出博览会以对 native 使用react

javascript - 在 React Native 中渲染 array.map

javascript - 什么在数据消耗方面更有效率。获取还是发布?