如何在反应原生状态下改变组件?

时间:2017-05-18 18:17:19

标签: reactjs react-native

我想创建一个包含按钮的简单页面。当我点击该按钮时,页面将更改为其他内容。

class LoginScreen extends Component {

    render() {
        return (
            <Button title='Login' onPress={() => 
                this.setState({ login: true})
            }/>
        );
    }

}

class LogoutScreen extends Component {

    render() {
        return (
            <Button title='Logout' onPress={() => 
                this.setState({ login: false})
            }/>
        );
    }

}

class Screen extends Component {
    constructor(props){
        super(props);
        this.state = {login: false}
    }
    render(){
        return (
            <View>
            // I want to place LogoutScreen or LoginScreen here based on current state 
            </View>
        );
    }
}

如何根据当前状态在Screen组件中设置LoginScreen和LogoutScreen?

1 个答案:

答案 0 :(得分:5)

如果要开始在组件之间移动,可能需要考虑添加导航。另外,要更新父组件的状态,您需要将onPress移动到屏幕:

class Screen extends Component {
    constructor(props){
        super(props);
        this.state = {login: false}
    }
    toggleLogin = () => this.setState(prevState => ({ login: !prevState.login }))

    render(){
        return (
            <View>
              {this.state.login ? <LoginScreen toggleLogin={this.toggleLogin} /> :
                <LogoutScreen toggleLogin={this.toggleLogin} />}
            </View>
        );
    }
}
class LoginScreen extends Component {

    render() {
        return (
            <Button title='Login' onPress={this.props.toggleLogin}/>
        );
    }

}

class LogoutScreen extends Component {

    render() {
        return (
            <Button title='Logout' onPress={this.props.toggleLogin} />
        );
    }

}