以编程方式在 React Native 中添加组件 [英] Programmatically add a component in React Native

查看:21
本文介绍了以编程方式在 React Native 中添加组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个像这样的简单 React Native 应用程序:

Suppose I have a simple React Native app like so:

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  Text,
  TouchableHighlight,
  View,
} = React;

var ReactProject = React.createClass({
  _onPressOut: function() {
    // What do we do here?
  },

  render() {
    return (
      <View>
        <Text>This text should be before</Text>
        <Text>This text should be after</Text>
        <TouchableHighlight onPressOut={this._onPressOut}>
          <Text>Tap Me</Text>
        </TouchableHighlight>
      </View>
    );
  }
});

AppRegistry.registerComponent('ReactProject', () => ReactProject);

如何在按下 TouchableHighlight 时在第一个和第二个 Text 标签之间动态插入组件?

How can I dynamically insert a component between the first and second Text tags when the TouchableHighlight is pressed?

推荐答案

尝试创建一个数组并将其附加到状态.然后您可以将项目推送到数组,并重置状态.

Try creating an array and attaching it to the state. You can then push items to the array, and reset the state.

https://rnplay.org/apps/ymjNxQ

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableHighlight
} = React;

var index = 0

var SampleApp = React.createClass({

  getInitialState(){
    return { myArr: [] }
  },

  _onPressOut() {
    let temp = index ++
    this.state.myArr.push(temp)
    this.setState({
        myArr: this.state.myArr
    })
  },

  render() {

    let Arr = this.state.myArr.map((a, i) => {
      return <View key={i} style={{ height:40, borderBottomWidth:2, borderBottomColor: '#ededed' }}><Text>{ a }</Text></View>                            
    })    
    return (
      <View style={styles.container}>
        <Text>First</Text>
        { Arr }
        <Text>Second</Text>
        <TouchableHighlight style={ styles.button } onPress={ () => this._onPressOut() }>
            <Text>Push</Text>
        </TouchableHighlight>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop:60
  },
  button: {
    height:60,
    backgroundColor: '#ededed',
    marginTop:10,
    justifyContent: 'center',
    alignItems: 'center'
  }
});

AppRegistry.registerComponent('SampleApp', () => SampleApp);

我在此处设置了一个工作示例.

I've set up a working example here.

这篇关于以编程方式在 React Native 中添加组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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