【问题标题】:How to get Text component value onPress in react-naive如何在 react-native 中获取文本组件值 onPress
【发布时间】:2019-09-01 16:37:51
【问题描述】:

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

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


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

【问题讨论】:

标签: javascript reactjs react-native react-props


【解决方案1】:

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

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

【讨论】:

  • 仅供参考,对于onLongPress,显然正确的字段是event._targetInst.memoizedProps.children。
【解决方案2】:

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

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

&lt;Text ref={(elem) =&gt; this.textElem = elem} onPress={()=&gt;this.display}&gt;Hello World&lt;/Text&gt;

对于您的事件处理程序,您可以这样做

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

【讨论】:

    【解决方案3】:
    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>
    

    打印出来

    【讨论】:

      【解决方案4】:

      您需要可以使用 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);
      }
      

      【讨论】:

        【解决方案5】:
        <Text onPress={()=>this.display('Hello World')}></Text>
        
        
        display= (text) =>{
            console.log(text);//this should print Hello world
          }
        

        试试这个

        【讨论】:

        • 您的代码显示硬编码文本“Hello World”,该代码不显示 Text 元素值。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-25
        • 2021-05-08
        • 2021-01-23
        • 2021-02-24
        • 2020-10-26
        相关资源
        最近更新 更多