gpt4 book ai didi

react-native - 按下按钮时如何更改状态?

转载 作者:行者123 更新时间:2023-12-04 04:17:48 26 4
gpt4 key购买 nike

我是React Native的新手,对js不熟悉。

我希望程序显示我按TextInput时在Button中写的内容(Text下方有一个Button)。我想也许我应该进入两个状态:将state1 text作为Text输入,并将state2 mimin作为TextInput输入,以及当Button pressed时,将state2 mimin放入state1 text

我尝试使用下面的代码,但是当我单击Button时,它给了我红页。

import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
Button,
TextInput,
Alert,
View
} from 'react-native';

export default class Hella extends Component {

constructor(props) {
super(props);
this.state = {text: '', mimin: ''};
}

render() {
return (
<View style={styles.container}>

<TextInput
style={{height: 40}}
placeholder="Type here to translate!"
onChangeText={(mimin) => this.setState({mimin})}
/>
<Button
onPress={onButtonPress}
title="Learn More"
color="#841584"
accessibilityLabel="Learn more about this purple button"
/>
<Text style={styles.instructions}>
{this.state.text}
</Text>
</View>
);
}
}

const styles = StyleSheet.create({
container: {
backgroundColor: '#F5FCFF',
}
});

const onButtonPress = () => {
Hella.setState({
text: Hella.state.mimin -------> where the error happened
});
};

AppRegistry.registerComponent('Hella', () => Hella);

错误是
undefined is not an object (evaluating 'Hella.state.mimin')

onButtonPress
<project location>/index.android.js:61

我做错了什么?我应该如何申报?在哪里可以了解更多?

最佳答案

您的onButtonPress应该在class内,因为您想执行setState

export default class Hella extends Component {
constructor(props) {
...
}

onButtonPress = () => {
this.setState({
text: this.state.mimin
});
}

render() {
return (
...
<Button
onPress={this.onButtonPress}
...
/>
...
);
}
}

React Native使用了很多React概念。学习React的基础知识将对您有很多帮助

关于react-native - 按下按钮时如何更改状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40521388/

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