在React Native中渲染另一个视图

时间:2016-03-23 19:51:43

标签: javascript reactjs react-native button view

我在React Native中渲染另一个视图时出现问题。

目前,我试图在点击按钮时显示另一个视图(渲染另一个视图)。这是我的React Native代码:

'use strict';
var React = require('react-native');
var {
    AppRegistry,
    StyleSheet,
    View,
    Text,
    ScrollView,
    Image,
    TextInput,
    Button
} = React;


var Button = require('./node_modules/react-native-button');
var TemplateApp = React.createClass({
    _handlePress: function(event) {    
        // CODE TO DISPLAY ANOTHER VIEW
    },

    render: function() {
        return ( 
            <View>
                <Button style = 
                    {{
                        fontSize: 20,
                        height: 40,
                        padding: 5,
                        margin: 10,
                        backgroundColor: 'black',
                        color: 'green'
                    }}
                    styleDisabled = {{color: 'red'}}
                    onPress = {
                        this._handlePress
                    } 
                >
                Sign In 
                </Button>
            </View>
        );
    }
});



var homeApp = React.createClass({
    render: function() {
        return ( < View >
            < Text > Welcome Home < /Text> < /View>
        )
    }
})

AppRegistry.registerComponent('App', () => TemplateApp);

单击按钮inside the _handlePress function我想显示主视图。任何人都可以指出如何做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以使用状态解决它并相应地呈现不同的内容。像这样:

var TemplateApp = React.createClass({

getInitialState: function() {
   return {buttonPressed: false};
},

_handlePress: function(event) {
    this.setState({buttonPressed: true}
},



render: function() {
   if (!this.state.buttonPressed) {
    return ( < View >
        < Button style = {
            {
                fontSize: 20,
                height: 40,
                padding: 5,
                margin: 10,
                backgroundColor: 'black',
                color: 'green'
            }
        }
        styleDisabled = {
            {
                color: 'red'
            }
        }
        onPress = {
            this._handlePress
        } >
        Sign In < /Button>

        < /View>
    );}
   else {
      return <HomeApp />
    }
}

});



var HomeApp = React.createClass({
    render: function() {
        return ( < View >
            < Text > Welcome Home < /Text> < /View>
        )
    }
})

AppRegistry.registerComponent('App', () => TemplateApp);