2016-11-10 64 views
3

我是React Native的新手,不熟悉js。按钮按下时如何改变状态?

我想让程序显示我在TextInput中按下ButtonButton下面有Text)写的内容。我想也许我应该做两个状态:把状态1 text作为Text输入,并把状态2 mimin作为TextInput输入,当按钮pressed,把状态2 mimin状态1 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 

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

回答

5

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

+0

最后它的工作!再一次非常感谢你)! :)我也会尝试链接 – Konayuki