Is it possible to dynamically create components in React Native?

后端 未结 5 475
萌比男神i
萌比男神i 2021-02-04 06:40

Is it possible to dynamically create and add view components in React Native? For example, firstly I have only empty screen and information of all views come from server in JSO

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-04 06:58

    Here is another approach:-

    import { StatusBar } from 'expo-status-bar';
    import React from 'react';
    import { StyleSheet, Text, View } from 'react-native';
    
    
    const renderObject = {
      type : "View",
      children : [
        {
          type: "View",
          styles: {
            backgroundColor: "orange",
            flex:1,
            justifyContent:"center",
            alignItems: "center"
          },
          children: [
            {
              type: "Text",
              styles: {
                color: "yellow",
                fontSize: 20
              },
              text: "Hello"
            },
            {
              type: "View",
              styles: {
                backgroundColor: "red",
                width: 100,
                height: 5,
                marginTop: 10
              },
              children: []
            }
          ]
        },
        {
          type: "View",
          styles: {
            flex:1,
            justifyContent:"center",
            alignItems: "center"
          },
          children: [
            {
              type: "Text",
              styles: {
                color: "red",
                fontSize: 40
              },
              text: "Hello"
            }
          ]
        },
        {
          type: "View",
          styles: {
            flex:1,
            justifyContent:"center",
            alignItems: "center",
            backgroundColor: "green"
          },
          children: [
            {
              type: "Text",
              styles: {
                color: "white",
                fontSize: 80
              },
              text: "Hello"
            }
          ]
        }
      ],
      styles: {
        flex:1
      }
    }
    
    const CustomComp = (props) => {
      const {type} = props;
      if(type == "View"){
        const {styles, children} = props;
        return {children.map((item) => CustomComp(item))}
      } else if(type == "Text") {
        const {styles, text} = props;
        return {text}
      }
    }
    
    export default function App() {
      return (
        
          {CustomComp(renderObject)}
          
        
      );
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: '#fff',
        justifyContent: 'center',
      },
    });
    

    You can find the full code on this Repo.

提交回复
热议问题