Programmatically add a component in React Native

后端 未结 4 1622
忘掉有多难
忘掉有多难 2020-12-09 04:35

Suppose I have a simple React Native app like so:

\'use strict\';

var React = require(\'react-native\');
var {
  AppRegistry,
  Text,
  TouchableHighlight,
         


        
4条回答
  •  失恋的感觉
    2020-12-09 05:13

    Try creating an array and attaching it to the state. You can then push items to the array, and reset the state.

    https://rnplay.org/apps/ymjNxQ

    'use strict';
    
    var React = require('react-native');
    var {
      AppRegistry,
      StyleSheet,
      Text,
      View,
      TouchableHighlight
    } = React;
    
    var index = 0
    
    var SampleApp = React.createClass({
    
      getInitialState(){
        return { myArr: [] }
      },
    
      _onPressOut() {
        let temp = index ++
        this.state.myArr.push(temp)
        this.setState({
            myArr: this.state.myArr
        })
      },
    
      render() {
    
        let Arr = this.state.myArr.map((a, i) => {
          return { a }                            
        })    
        return (
          
            First
            { Arr }
            Second
             this._onPressOut() }>
                Push
            
          
        );
      }
    });
    
    var styles = StyleSheet.create({
      container: {
        flex: 1,
        marginTop:60
      },
      button: {
        height:60,
        backgroundColor: '#ededed',
        marginTop:10,
        justifyContent: 'center',
        alignItems: 'center'
      }
    });
    
    AppRegistry.registerComponent('SampleApp', () => SampleApp);
    

    I've set up a working example here.

提交回复
热议问题