一個好的方法是設置一個數組,然後映射視圖中的數組。要添加元素,推動項目的陣列和重置陣列的狀態:
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>
})
而且使用這樣的變量:
<View>
{ rows }
</View>
我已經建立了這樣一個工作示例here,並粘貼下面的代碼。
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);
這是否運行每一行的映射功能,每次你添加行?這不是多餘的嗎? – Waltari