How to get Text component value onPress in react-naive

心不动则不痛 提交于 2020-07-22 12:21:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!