React Native - 按下按钮时将元素动态添加到 DOM [英] React Native - Dynamically Add Element to DOM on button press

查看:40
本文介绍了React Native - 按下按钮时将元素动态添加到 DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 React Native 中,我试图通过单击按钮将元素动态添加到 DOM.

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

这是我目前在 Render() 方法中的内容:

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

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

        <Text>Add new row</Text>

</TouchableHighlight>

我不确定从 onpress 函数返回什么来添加另一个 DOM 元素:

I'm not sure what to return from the onpress function to add another DOM element:

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

有什么帮助吗?

推荐答案

一个很好的方法是设置一个数组,然后在视图中通过该数组进行映射.要添加一个元素,将一个项目推入数组并重置数组的状态:

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

并像这样使用变量:

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

这篇关于React Native - 按下按钮时将元素动态添加到 DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆