【问题标题】:React native:how to get Text value on a button click?React native:如何在单击按钮时获取文本值?
【发布时间】:2018-01-11 12:13:05
【问题描述】:

我有一个Text,我想在点击时获取文本值。

例如

click()
{
    // how to get text value here 
}

<Text style={{color: 'red,textAlign:'center'}} onPress={this.click.bind(this)}>
    Name
</Text> 

【问题讨论】:

    标签: react-native


    【解决方案1】:

    这种方式也可以……

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

    【讨论】:

      【解决方案2】:

      您可以使用 ref 属性来访问 Text 的值。

      <Text ref='myText'>This is my text</Text>
      <Button onPress={()=>alert(this.refs.myText.props.children)} title='Press Me'/>
      

      【讨论】:

      • 让我知道如何处理动态文本
      • 如果您想使用动态@Himanshu Dwivedi 答案对您有好处。使用状态来存储动态值。要更改状态,只需在组件内您想要的任何函数上使用 this.setState({titleText:'This is new value'})。
      【解决方案3】:

      您可以维护状态内的文本并在单击按钮时获取文本值。

      export default class SampleApp extends Component{
      
        constructor(props){
          super(props);
          this.state = {
            titleText: "Click to get text! - ",
            count:1
          };
        }
      
        render() {
          return (
            <View style={{flex:1}}>
              <Text style={{color:'black'}} onPress={()=>{this.onPressTitle()}}>
                {this.state.titleText}
              </Text>
            </View>
          );
        }
      
        onPressTitle(){
          alert(this.state.titleText+this.state.count);
          this.setState({count:this.state.count+1});
        }
      }
      

      适用于动态文本。

      【讨论】:

        【解决方案4】:

        对我来说,它与 console.log(event._dispatchInstances.memoizedProps.children[0].props.children) 合作过

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-04-16
          • 1970-01-01
          • 2017-12-15
          • 2019-08-05
          • 2018-03-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多