如何在 react-native 中获取 Text 组件值 onPress

How to get Text component value onPress in react-naive

我是一名新的 React-Native 开发人员。我想使用 onPress 获取 Text 组件的值并将其传递给函数。

<Text onPress={()=>this.display}>Hello World</Text>


display= (text) =>{
    console.log(text);//this should print Hello world
  }

您需要可以使用 ref 属性来访问按钮的文本值。

<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);
}

或者,只需将其存储在一个变量中:

const myText = "This is my text"

<Text onPress={()=>this.display}>{myText}</Text>

display = () => {
     console.log(myText);
}

我不是 React Native 方面的专家。我从这个

中得到了一些想法

但我认为你可以在 Text 组件上设置一个 ref

<Text ref={(elem) => this.textElem = elem} onPress={()=>this.display}>Hello World</Text>

对于您的事件处理程序,您可以执行

display = () =>{
    console.log(this.textElem.props.children);//this should print Hello world
}
<Text onPress={()=>this.display('Hello World')}></Text>


display= (text) =>{
    console.log(text);//this should print Hello world
  }

试试这个

此方法可用于从文本 onPress 事件中获取文本

 <Text onPress={(event) => console.log(event._dispatchInstances.memoizedProps.children)} >{value}</Text>
onPress={(e) => console.log(e, word)}

Class {dispatchConfig: {…}...} 'word'

word参数携带组件内部文本的值,e携带事件对象

实际例子:

const wordSelected = (e, word) => {
    console.log(word);
  };

  <TouchableOpacity onPress={(e) => wordSelected(e, word)}>
              <Text>print me out</Text>
            </TouchableOpacity>

print me out