gpt4 book ai didi

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

转载 作者:技术小花猫 更新时间:2023-10-29 10:59:43 26 4
gpt4 key购买 nike

我是一名 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: {}
});

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

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

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

最佳答案

您可以使用一个状态来保留您的默认文本,然后按下我们更新状态。

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

关于javascript - 如何在 React Native 中按下按钮时更改文本值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45041577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com