Reactjs 如何获取文本组件中的文本onPress in react native

Reactjs 如何获取文本组件中的文本onPress in react native,reactjs,react-native,Reactjs,React Native,我想获取“text”组件“onPress”中的文本,并将其设置为组件的状态变量。这是我的密码- var MyComponent = React.createClass({ getInitialState: function(){ return { myStateVariable: 'New York' } }, render: function(){ return ( <Text onPress={()

我想获取“text”组件“onPress”中的文本,并将其设置为组件的状态变量。这是我的密码-

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>
    );
}   
});
var MyComponent=React.createClass({
getInitialState:函数(){
返回{
mystate变量:“纽约”
}
},   
render:function(){
报税表(
{
这是我的国家({
myStateVariable:'London'//这很好用
myStateVariable:this.children//这不起作用
});
}  
}>
伦敦
{this.state.myStateVariable}
);
}   
});

如何动态获取“文本”组件中的文本?

根据您对我的评论的反馈,您应该尝试这样编写MyComponent-

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>
      );
  }   
});
var MyComponent=React.createClass({
onPress:功能(i){
让city=this.props.cities[i];
//对城市做点什么。
},
renderCities:function(){
this.props.cities.map((city,i)=>{
返回{城市};
});
},
render:function(){
返回(
{this.renderCities()}
);
}   
});

this.children中的这个实际上指向MyComponent,因此它将返回未定义。奇怪的是,如果在chrome开发工具中的this.setState中检查这个,它实际上指向当前的“Text”组件对象(带有属性children),并且它没有setState方法,它仍然调用setState方法。这是一个实际的代码片段还是您编写它是为了以不同的方式解释您的原始问题?我这样问是因为MyComponent已经知道文本组件中的内容。为什么需要从文本中提取它?您可以改为将值存储在类变量中并访问它。@HazardouS-此代码几乎类似。在我的实际代码中,我有多个文本组件,其中城市在数组中动态迭代呈现。在触摸/按下特定文本组件时,我希望文本在其中。它不起作用,所以我创建了这个简单的组件用于测试,但仍然面临相同的问题。添加了一个可能的模式作为答案。它起作用了!。但我不明白它是怎么工作的?bind(这个,我)是如何解决这个问题的。你能再解释一下吗?当然。它是这样工作的。。。顶级组件中已经有了数组,并且每个子元素都与一个数组元素链接。因此,只要将元素索引发送给click处理程序,我们就可以找到单击了哪个元素。
bind
调用基于上下文函数返回一个新函数,将给定输入转换为原始函数参数的默认值。因此,本质上我们创建了“n”个不同的函数,每个函数向原始函数发送不同的索引。一个更好的选择是将索引存储在prop中,并在onPress处理程序中获取它。