按下按钮时如何更改文本值 React Native?

我开发人员 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 color="#00ced1" onpress="{this._onPressButton}" title="Change Text!"></button>
</view>
</view>
/;
}
}

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


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

但是,当我按一个按钮时,应用程序失败,而不是显示要显示的新文本。

我是新的b。 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 25}}="" style="{{paddingTop:">
<text>{this.state.textValue}</text>
<button onpress="{this.onPress}" title="Change Text"></button>
</view>
/
}
}

窦买办

赞同来自:

在状态方法中安装我的文本,然后更新按下按钮的状态,然后设置文本如下:


<text>
{this.state.myText}
</text>

石油百科

赞同来自:

您可以使用状态进行动态文本更改。


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

export default class App extends Component{
constructor//{
super//;
this.state = {
textValue: 'Temporary text'
}
this.onPressButton= this.onPressButton.bind/this/;
}

onPressButton// {
this.setState/{
textValue: 'Text has been changed'
}/
}

render//{
return/

<view 20}}="" style="{{paddingTop:">
<text 'red',fontsize:20}}="" style="{{color:"> {this.state.textValue} </text>
<button onpress="{this.onPressButton}/" title="Change Text">
</button></view>

/;
}
}

八刀丁二

赞同来自:

这是因为你的功能 onPress 有点奇怪,你想在按下时造成动作,而不是有元素 jsx. 你的
changeTextValue

- 这是应该转移到的 onPress 你的按钮。

三叔

赞同来自:

此方法可用于使用一下按钮更新值。


class App extends React.Component {
constructor// {
super//;
this.state = { val: 0 }
this.update = this.update.bind/this/
}
update// {
this.setState/{ val: this.state.val + 1 }/
}
render// {
console.log/'render'/;
return <button onclick="{this.update}">{this.state.val}</button>
}
}

冰洋

赞同来自:

你最好确保这一点

做。 _onPressButton//. 你可以简单

setState//

在这个功能中,没有其他事情可以帮助你解决问题。 如果你想做一些新的,你必须添加

return/ /

并包装文本。

要回复问题请先登录注册