In my App.js, I have initialized some states like so,
export default class App extends React.Component {
constructor(){
super();
this.state = {
myfirststate: '',
mysecondstate: '',
}
}
...
}
Now I have a ChildComponent.js which is stateless and is like this which has a button and when clicked, changes the state of myfirststate
from null to hello
.
export default class ChildComponent extends React.Component {
render() {
return (
<View>
<Button
title="clickme"
onPress={() =>
this.setState({myfirststate: "hello"})
/>
</View>
);
}
}
Is it possible to do something like this? I always thought I had to pass the value of states as arguements in a function which was passed from parent component to child like this instead.
App.js
export default class App extends React.Component {
constructor(){
super();
this.state = {
myfirststate: '',
mysecondstate: '',
}
}
functiontopassvalues(values) {
this.setState({
myfirststate: values
})
}
<ChildComponent functiontopassvalues={this.functiontopassvalues} />
}
And in ChildComponent.js
I would do something like this
export default class ChildComponent extends React.Component {
render() {
return (
<View>
<Button
title="clickme"
onPress={() =>
{this.props.functiontopassvalues("hello")}
/>
</View>
);
}
}
I hope I am making sense, please let me know what is the correct method to do it and why it is so. Also, does it apply to both react native and react.js?