Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
128 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...