按下按钮时如何更改状态?

时间:2016-11-10 06:42:16

标签: react-native

我是React Native的新手并且不熟悉js。

当我按下TextInputButton下面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

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

2 个答案:

答案 0 :(得分:9)

您的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的基础知识将为您提供很多帮助https://facebook.github.io/react/tutorial/tutorial.html

答案 1 :(得分:0)

函数定义应如下所示。

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