2016-06-09 71 views
1

所以考慮以下幾點:我忘了如何在React中設置初始狀態嗎? (陣營本地)

import React, { Component } from 'react'; 

import { 
    AppRegistry, 
    StyleSheet, 
    Text, 
    View, 
    TextInput, 
    TouchableOpacity 
} from 'react-native'; 

class CreateTweet extends Component { 

    getInitialState() { 
    return { 
     text: 'Fake Value' 
    } 
    } 

    render() { 
    console.log(this.state); 
    return(
     <View style={styles.container}> 
     </View> 
    ) 
    } 
} 

const styles = StyleSheet.create({ 
    container: { 
    flex: 1, 
    marginTop: 100, 
    alignItems: 'center', 
    backgroundColor: '#F5FCFF', 
    }, 
    welcome: { 
    fontSize: 20, 
    textAlign: 'center', 
    margin: 10, 
    }, 
}); 

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

module.exports = CreateTweet; 

運行時的狀態是null。你可以看到console.log(this.state)我正在設置組件初始化時的狀態,這是怎麼回事?有沒有一些魔術我不知道在React本地那不同於React?

回答

4

由於您使用的類,你的國家應該在構造函數中進行設置:

constructor (props) { 
    super(props) 
    this.state = { 
     text: 'Fake Value' 
    } 
} 
+2

你也仍然可以使用'React.createClass'如果你喜歡的方式! – spro

+0

這是我以爲我失蹤>>謝謝 – TheWebs