Is it possible to dynamically create components in React Native?

后端 未结 5 481
萌比男神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 07:11

    React docs (and by extension it could be done with ReactNative too) show how to choose the component type at runtime:

    import React from 'react';
    import { PhotoStory, VideoStory } from './stories';
    
    const components = {
      photo: PhotoStory,
      video: VideoStory
    };
    
    function Story(props) {
      const SpecificStory = components[props.storyType];
      return ;
    }
    

    Doing so, you could just only need to walk on your JSON tree and just create the ReactNative components, using the components object as a mapping between the type defined in the JSON tree and their constructors.

提交回复
热议问题