Ad

How To Get Text Inside Text Component OnPress In React-native

- 1 answer

I want to get text inside 'Text' component 'onPress' and set it to my component's state variable. Here is my code -

var MyComponent = React.createClass({
getInitialState: function(){
    return {   
        myStateVariable: 'New York'        
    }
},   
render: function(){
    return (  
        <Text onPress={()=>{
               this.setState({
                   myStateVariable: 'London' // This works fine
                   myStateVariable: this.children // This is not working
               });
             }  
        }>
            London
        </Text>
        <Text>{this.state.myStateVariable}</Text>
    );
}   
});

How to get the text inside 'Text' component dynamically?

Ad

Answer

Based on your feedback to my comment, you should try writing MyComponent like this -

var MyComponent = React.createClass({
  onPress:function(i){
    let city = this.props.cities[i];
    // do something with city.
  },
  renderCities:function(){
    this.props.cities.map((city, i)=>{
      return <Text key={i} onPress={this.onPress.bind(this, i)}>{city}</Text>;
    });
  },
  render: function(){
      return (
        <div>
          {this.renderCities()}
        </div>
      );
  }   
});
Ad
source: stackoverflow.com
Ad