2016-11-10 88 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