Reputation: 945
I want to create a simple page which contain a button. When i click that button, the page will changed to something else.
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>
);
}
}
How to set the LoginScreen and LogoutScreen inside Screen component based on the current state?
Upvotes: 1
Views: 6898
Reputation: 8936
You might want to think about adding navigation if you want to start moving between components. Also to update the state on the parent component, you would need to move the onPress into Screen:
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} />
);
}
}
Upvotes: 6