javascript – 如何在React Native中按下按钮时更改文本值?

前端之家收集整理的这篇文章主要介绍了javascript – 如何在React Native中按下按钮时更改文本值?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_404_1@我是iOS开发人员,目前正在开发一个实验性的React Native应用程序.
我有以下代码,在屏幕上显示一个按钮和示例文本.
import React from 'react';
import { StyleSheet,Text,View,Button } from 'react-native';

export default class App extends React.Component {
  constructor() {
    super();
    this.state = {sampleText: 'Initial Text'};
  }

  changeTextValue = () => {
    this.setState({sampleText: 'Changed Text'});
  }

  _onPressButton() {
    <Text onPress = {this.changeTextValue}>
      {this.state.sampleText}
    </Text>
  }

  render() {
    return (
      <View style={styles.container}>
        <Text onPress = {this.changeTextValue}>
          {this.state.sampleText}
        </Text>

        <View style={styles.buttonContainer}>
          <Button
            onPress={this._onPressButton}
            title="Change Text!"
            color="#00ced1"
          />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,backgroundColor: '#f5deb3',alignItems: 'center',justifyContent: 'center',},buttonContainer: {}
});

上面的代码显示文本和按钮.

However when I click the button,the app crashes instead of showing the new text which is to be shown.

我是React Native的新手,请指导我如何解决错误.

解决方法

您可以使用状态来保留默认文本,然后按下我们更新状态
import React,{Component} from 'react';
import {View,Button} from 'react-native';

export default class App extends Component{
    constructor(){
        super();
        this.state = {
            textValue:'Change me'
        }
    }

    onPress = () => {
        this.setState({
            textValue: "THE NEW TEXT GOES HERE"
        })
    }

     render(){
        return(
        <View style={{paddingTop: 20}}>
            <Text style={{color: 'cyan'}}>{this.state.textValue}</Text>
            <Button title="Change Text" onPress={this.onPress}/>
        </View>
        );
    }
}

Dhu字节:您以前的答案代码不起作用.您还应该导入View组件.我做了改变,所以,它现在正在工作.

原文链接:https://www.f2er.com/js/150854.html

猜你在找的JavaScript相关文章