【问题标题】:React Native - Dynamically Add Element to DOM on button pressReact Native - 在按钮按下时动态地将元素添加到 DOM
【发布时间】:2016-06-02 03:09:00
【问题描述】:

在本机反应中,我试图在单击按钮时将元素动态添加到 DOM。

这是我目前在 Render() 方法中所拥有的:

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

        <Text>Add new row</Text>

</TouchableHighlight>

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

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

有什么帮助吗?

【问题讨论】:

    标签: react-native


    【解决方案1】:

    这样做的一个好方法是设置一个数组,然后在视图中映射该数组。要添加元素,请将项目推送到数组并重置数组的状态:

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

    【讨论】:

    • 每次添加一行时,是否都会为每一行运行映射函数?这不是多余的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    • 2018-05-21
    • 2017-11-08
    • 2017-10-15
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    相关资源
    最近更新 更多