React Native - Dynamically Add Element to DOM on button press

后端 未结 1 443
醉梦人生
醉梦人生 2021-01-11 13:35

In react native i\'m trying to dynamically add an element to the DOM on a button click.

This is what I have so far in the Render() method:



        
相关标签:
1条回答
  • 2021-01-11 14:21

    A good way to do this is to set up an array and then map through the array in the view. To add an element, push an item to the array and reset the state of the array:

    getInitialState(){
      return { rows: [] }
    },
    
    _addRow(){
      this.state.rows.push(index++)
      this.setState({ rows: this.state.rows })
    }
    
    let rows = this.state.rows.map((r, i) => {
        return <View key={ i } style={[styles.row, CheckIndex(i)]}>
                  <Text >Row { r }, Index { i }</Text>
               </View>
    })
    

    And use the variable like this:

    <View>
      { rows }
    </View>
    

    I've set up a working example of this here, and pasted the code below as well.

    https://rnplay.org/apps/-ENWEw

    'use strict';
    
    var React = require('react-native');
    var {
      AppRegistry,
      StyleSheet,
      Text,
      View,
      TouchableHighlight
    } = React;
    
    let index = 0 
    
    var SampleApp = React.createClass({
    
      getInitialState(){
            return { rows: [] }
        },
    
      _addRow(){
        this.state.rows.push(index++)
        this.setState({ rows: this.state.rows })
      },
    
      render() {
    
        let CheckIndex = i => {
            if((i % 2) == 0) {
            return styles.gray
          }
        }
    
        let rows = this.state.rows.map((r, i) => {
            return <View key={ i } style={[styles.row, CheckIndex(i)]}>
                        <Text >Row { r }, Index { i }</Text>
                     </View>
        })
    
        return (
          <View style={styles.container}>
            <TouchableHighlight onPress={ this._addRow } style={styles.button}>
                <Text>Add new row</Text>
                    </TouchableHighlight>
            { rows }
          </View>
        );
      }
    });
    
    var styles = StyleSheet.create({
      container: {
        flex: 1,
        marginTop: 60,
      }, 
      gray: {
        backgroundColor: '#efefef'
      },
      row: {
        height:40,
        alignItems: 'center',
        justifyContent: 'center',
        borderBottomColor: '#ededed',
        borderBottomWidth: 1
      },
      button: {
        alignItems: 'center',
        justifyContent: 'center',
        height:55,
        backgroundColor: '#ededed',
        marginBottom:10
      }
    });
    
    AppRegistry.registerComponent('SampleApp', () => SampleApp);
    
    0 讨论(0)
提交回复
热议问题