2016-02-20 32 views
10

In risposta nativo, sto provando ad aggiungere un elemento al DOM in modo dinamico con un clic del pulsante.Reagire Nativo - Aggiungere dinamicamente un elemento al DOM sul pulsante premere

Questo è quello che ho finora nel metodo Render():

<TouchableHighlight 
    style={styles.button} 
    onPress={this.addAnotherRow}> 

     <Text>Add new row</Text> 

</TouchableHighlight> 

Non sono sicuro di quello che per tornare dalla funzione onPress per aggiungere un altro elemento DOM:

addAnotherRow() { 
    return <Text>New Row</Text> 
} 

Qualche aiuto per favore?

risposta

6

Un buon modo per fare ciò è configurare un array e quindi mappare attraverso l'array nella vista. Per aggiungere un elemento, spingere un elemento alla matrice e ripristinare lo stato della matrice:

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> 
}) 

E utilizzare la variabile in questo modo:

<View> 
    { rows } 
</View> 

ho creato un esempio di lavoro di questo here e incollato anche il codice sottostante.

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

Questo esegue la funzione di mappatura per ogni riga ogni volta che si aggiunge una riga? Non è ridondante? – Waltari

Problemi correlati