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);
fonte
2016-02-20 15:08:06
Questo esegue la funzione di mappatura per ogni riga ogni volta che si aggiunge una riga? Non è ridondante? – Waltari