Reputation: 33
I'm a new react-native developer. I want to get the value of Text component using onPress and pass it to a function.
<Text onPress={()=>this.display}>Hello World</Text>
display= (text) =>{
console.log(text);//this should print Hello world
}
Upvotes: 3
Views: 7214
Reputation: 36
onPress={(e) => console.log(e, word)}
Class {dispatchConfig: {…}...} 'word'
word argument will carry the value of the component inner text, and the e will carry the event object.
practical example:
const wordSelected = (e, word) => {
console.log(word);
};
<TouchableOpacity onPress={(e) => wordSelected(e, word)}>
<Text>print me out</Text>
</TouchableOpacity>
print me out
Upvotes: 1
Reputation: 351
This method can be used to get text from a text onPress event
<Text onPress={(event) => console.log(event._dispatchInstances.memoizedProps.children)} >{value}</Text>
Upvotes: 9
Reputation: 5450
<Text onPress={()=>this.display('Hello World')}></Text>
display= (text) =>{
console.log(text);//this should print Hello world
}
Try this
Upvotes: -3
Reputation: 2858
I'm not an expert on React Native. I got some ideas from this Stackoverflow Link
But I think you can set up a ref
on the Text
component
<Text ref={(elem) => this.textElem = elem} onPress={()=>this.display}>Hello World</Text>
For your event handler, you can do
display = () =>{
console.log(this.textElem.props.children);//this should print Hello world
}
Upvotes: 2
Reputation: 571
You need can use the ref attribute to access the button's Text value.
<Text ref='myText'>This is my text</Text>
<Button onPress={()=>this.display(this.refs.myText.props.children)} title='Press Me'/>
//this should print Hello world
display= (text) =>{
console.log(text);
}
Alternatively, just store it in a variable:
const myText = "This is my text"
<Text onPress={()=>this.display}>{myText}</Text>
display = () => {
console.log(myText);
}
Upvotes: 0