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

IT技术 javascript reactjs react-native react-props
2021-05-22 23:07:03

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

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


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

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

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

我不是 React Native 的专家。我从这个Stackoverflow Link 中得到了一些想法

但我认为你可以refText组件设置一个

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

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

display = () =>{
    console.log(this.textElem.props.children);//this should print Hello world
}
onPress={(e) => console.log(e, word)}

类 {dispatchConfig: {...}...} 'word'

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

实际例子:

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

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

打印出来

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

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