【发布时间】:2018-01-11 12:13:05
【问题描述】:
我有一个Text,我想在点击时获取文本值。
例如
click()
{
// how to get text value here
}
<Text style={{color: 'red,textAlign:'center'}} onPress={this.click.bind(this)}>
Name
</Text>
【问题讨论】:
标签: react-native
我有一个Text,我想在点击时获取文本值。
例如
click()
{
// how to get text value here
}
<Text style={{color: 'red,textAlign:'center'}} onPress={this.click.bind(this)}>
Name
</Text>
【问题讨论】:
标签: react-native
这种方式也可以……
<Text onPress={(event) => console.log(event._dispatchInstances.memoizedProps.children)} >{value}</Text>
【讨论】:
您可以使用 ref 属性来访问 Text 的值。
<Text ref='myText'>This is my text</Text>
<Button onPress={()=>alert(this.refs.myText.props.children)} title='Press Me'/>
【讨论】:
您可以维护状态内的文本并在单击按钮时获取文本值。
export default class SampleApp extends Component{
constructor(props){
super(props);
this.state = {
titleText: "Click to get text! - ",
count:1
};
}
render() {
return (
<View style={{flex:1}}>
<Text style={{color:'black'}} onPress={()=>{this.onPressTitle()}}>
{this.state.titleText}
</Text>
</View>
);
}
onPressTitle(){
alert(this.state.titleText+this.state.count);
this.setState({count:this.state.count+1});
}
}
适用于动态文本。
【讨论】:
对我来说,它与 console.log(event._dispatchInstances.memoizedProps.children[0].props.children) 合作过
【讨论】: