问题
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
}
回答1:
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
}
回答2:
This method can be used to get text from a text onPress event
<Text onPress={(event) => console.log(event._dispatchInstances.memoizedProps.children)} >{value}</Text>
回答3:
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);
}
回答4:
<Text onPress={()=>this.display('Hello World')}></Text>
display= (text) =>{
console.log(text);//this should print Hello world
}
Try this
来源:https://stackoverflow.com/questions/57747744/how-to-get-text-component-value-onpress-in-react-naive