React native React Native-在按下按钮时将元素动态添加到DOM
在react native中,我尝试通过单击按钮向DOM动态添加元素 这是到目前为止我在Render()方法中得到的结果:React native React Native-在按下按钮时将元素动态添加到DOM,react-native,React Native,在react native中,我尝试通过单击按钮向DOM动态添加元素 这是到目前为止我在Render()方法中得到的结果: 添加新行 我不确定从onpress函数返回什么来添加另一个DOM元素: addAnotherRow() { return <Text>New Row</Text> } addAnotherRow(){ 返回新行 } 有什么帮助吗?一个好方法是设置一个数组,然后在视图中映射数组。要添加元素,请将项目推送到数组并重置数组的状态: getI
添加新行
我不确定从onpress函数返回什么来添加另一个DOM元素:
addAnotherRow() {
return <Text>New Row</Text>
}
addAnotherRow(){
返回新行
}
有什么帮助吗?一个好方法是设置一个数组,然后在视图中映射数组。要添加元素,请将项目推送到数组并重置数组的状态:
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>
})
getInitialState(){
返回{行:[]}
},
_addRow(){
this.state.rows.push(索引++)
this.setState({rows:this.state.rows})
}
让rows=this.state.rows.map((r,i)=>{
返回
行{r},索引{i}
})
并使用如下变量:
<View>
{ rows }
</View>
{rows}
我已经建立了一个工作示例,并粘贴了下面的代码
“严格使用”;
var React=require('React-native');
变量{
评估学,
样式表,
文本,
看法
可触摸高光
}=反应;
设指数=0
var SampleApp=React.createClass({
getInitialState(){
返回{行:[]}
},
_addRow(){
this.state.rows.push(索引++)
this.setState({rows:this.state.rows})
},
render(){
让CheckIndex=i=>{
如果((i%2)==0){
返回样式。灰色
}
}
让rows=this.state.rows.map((r,i)=>{
返回
行{r},索引{i}
})
返回(
添加新行
{rows}
);
}
});
var styles=StyleSheet.create({
容器:{
弹性:1,
玛金托普:60,
},
灰色:{
背景颜色:“#efefef”
},
行:{
身高:40,
对齐项目:“居中”,
为内容辩护:“中心”,
borderBottomColor:“#ededed”,
边框宽度:1
},
按钮:{
对齐项目:“居中”,
为内容辩护:“中心”,
身高:55,
背景颜色:“#ededed”,
marginBottom:10
}
});
AppRegistry.registerComponent('SampleApp',()=>SampleApp);
是否每次添加一行时都会为每一行运行映射功能?这不是多余的吗?
<View>
{ rows }
</View>
'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);