我想在'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>
);
}
});
如何动态获取“文本”组件中的文本?
答案 0 :(得分:4)
根据您对我的评论的反馈,您应该尝试像这样编写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>
);
}
});