我是一名iOS开发者,目前正在开发一款实验性的React原生apply.

我有下面的代码,在屏幕上显示一个按钮和示例文本.

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

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

但是,当我点击按钮时,应用程序崩溃,而不是显示要显示的新文本.

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

推荐答案

您可以使用状态来保留默认文本,然后按"我们更新状态".

import React, { Component } from 'react'
import { View, Text, Button } from 'react-native'

export default class App extends Component {
  state = {
    textValue: 'Change me'
  }

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

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

React-native相关问答推荐

在AWS-Amplify js v6中检索原始的accesToken和idToken

React native React native下拉 Select 器下拉列表不透明问题

哪个版本的@stripe/stripe-react-native 模块支持 react native 0.62.0 typscript 模板?

reactnavigation后退按钮的自定义后退导航

react-native-snap-carousel 无法正确渲染

找不到变量 atob

如何在 React Native 中测量我的应用程序的数据使用情况?

请求无法完成,因为您已超出配额

无法访问函数内部的状态

在 react-native 元素中更改 android 和 ios 的入口文件路径

redux-observable Promise 在单元测试中没有得到解决

FlatList contentContainerStyle -> justifyContent: 'center' 导致滚动问题

如何在 array.map 中的每个元素之后添加逗号,除了 React JSX 中的最后一个元素

React native Redux - 对象不是构造函数(判断'new ctor(props context)')

无法识别的 WebSocket 连接选项 `agent`、`perMessageDeflate`、`pfx`、`key`、`passphrase`... 你的意思是把这些放在 `headers` 下吗?

将 React Native 升级到 0.60-RC2 后找不到库libjsc.so

如何在 React Native 中重复图案图像以创建背景?

python 3与本机兼容吗?还是我应该按照 react 文档的建议安装 python 2?

react-native 开始给出 Invalid 正则表达式无效错误

/bin/sh: adb: 找不到命令