Home > Article > Web Front-end > What is state in React Native?
Status is the source of data. We should always try to keep our state as simple as possible and minimize the number of stateful components. For example, if we have 10 components that require state data, we should create a container component to hold the state of all these components.
When the user presses the button, the button title changes to ON/OFF.
The state is initialized inside the constructor as shown below -
constructor(props) { super(props); this.state = { isToggle: true }; }
isToggle is the boolean value assigned to the state. The button's title is determined based on the isToggle property. If the value is true, the button's title is ON, otherwise it is OFF.
When the button is pressed, the onpress method will be called, which will call setState that updates the isToggle value, as shown below-
onPress={() => { this.setState({ isToggle: !this.state.isToggle }); }}
When the user clicks the button, the onPress event will be called, And setState will change the state of the isToggle property.
App.js
import React, { Component } from "react"; import { Text, View, Button, Alert } from 'react-native'; class App extends Component { constructor(props) { super(props); this.state = { isToggle: true }; } render(props) { return ( <View style={{flex :1, justifyContent: 'center', margin: 15 }}> <Button onPress={() => { this.setState({ isToggle: !this.state.isToggle }); }} title={ this.state.isToggle ? 'ON' : "OFF" } color="green" /> </View> ); } } export default App;
The button will toggle when the user presses it.
Change the text when the user clicks on it.
In the following example, the state is displayed inside the constructor as follows-
constructor(props) { super(props); this.state = { myState: 'Welcome to Tutorialspoint' }; }
The state myState is displayed inside the Text component as follows-
<Text onPress={this.changeState} style={{color:'red', fontSize:25}}>{this.state.myState} </Text>
When the user touches Or when the text is pressed, the onPress event is triggered and the this.changeState method is called, which changes the text by updating the state myState as shown below -
changeState = () => this.setState({myState: 'Hello World'})
import React, { Component } from "react"; import { Text, View, Button, Alert } from 'react-native'; class App extends Component { constructor(props) { super(props); this.state = { myState: 'Welcome to Tutorialspoint' }; } changeState = () => this.setState({myState: 'Hello World'}) render(props) { return (); } } export default App; {this.state.myState}
The above is the detailed content of What is state in React Native?. For more information, please follow other related articles on the PHP Chinese website!