Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get text inside Text component onPress in react-native

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?

like image 793
C.P. Avatar asked Sep 25 '22 17:09

C.P.


1 Answers

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>
      );
  }   
});
like image 128
hazardous Avatar answered Sep 29 '22 00:09

hazardous