State works differently when compared to props. State is internal to a component, while props are passed to a component.
Keep in mind not to update state directly using this.state. Always use setState to update the state objects. Using setState re-renders the component and all the child components. This is great, because you don’t have to worry about writing event handlers like other languages.
class Form extends React.Component {
constructor (props) {
super(props)
this.state = {
input: ''
}
}
handleChangeInput = (text) => {
this.setState({ input: text })
}
render () {
const { input } = this.state
return (
onChangeText={this.handleChangeInput}
value={input}
/>
)
}
}
In the above code snippet you can see a Form class with an input state. It renders a text input which accepts the user’s input. Once the user inputs the text, the onChangeText is triggered which in turn calls setState on input.
References:
https://codeburst.io/props-and-state-in-react-native-explained-in-simple-english-8ea73b1d224e
Keep in mind not to update state directly using this.state. Always use setState to update the state objects. Using setState re-renders the component and all the child components. This is great, because you don’t have to worry about writing event handlers like other languages.
class Form extends React.Component {
constructor (props) {
super(props)
this.state = {
input: ''
}
}
handleChangeInput = (text) => {
this.setState({ input: text })
}
render () {
const { input } = this.state
return (
value={input}
/>
)
}
}
In the above code snippet you can see a Form class with an input state. It renders a text input which accepts the user’s input. Once the user inputs the text, the onChangeText is triggered which in turn calls setState on input.
References:
https://codeburst.io/props-and-state-in-react-native-explained-in-simple-english-8ea73b1d224e
No comments:
Post a Comment