How do I get a this.state.value from other components in react native
19,782
It should look like this.
class ClassOne extends React.Component {
constructor(props) {
super(props);
this.state = {
classtwo: 0,
};
}
componentWillReceiveProps(nextProps) {
if (nextProps.classtwo && (this.state.classtwo != nextProps.classtwo))
{this.setState({classtwo: nextProps.classtwo});}
}
}
class ClassTwo extends React.Component {
constructor(props) {
super(props);
this.changeValue = this. changeValue.bind(this);
this.state = {
value: 100,
};
}
changeValue(value){
this.props.changeValue(this.state.value);
this.setState(value: value);
}
}
class ClassZero extends React.Component {
constructor(props) {
super(props);
this.changeValue = this. changeValue.bind(this);
this.state = {
classTwoValue: 0,
};
}
changeValue(value){
this.setState(classTwoValue: value);
}
render() {
return (
<div>
<ClassOne classtwo={this.state.classTwoValue}/>
<ClassTwo changeValue={this.changeValue}/>
</div>
)
}
}
Author by
phongyewtong
Love Game and Fluttering Should I use Typescript instead of Javascript?
Updated on June 14, 2022Comments
-
phongyewtong almost 2 years
I got it to work calling getValue in classtwo from classone but is there another way of doing this? Is there a easier way to get this.state.value from classtwo?
I tried putting static getValue as static but it always throw me an error. Anyone can help?
Thanks!
class ClassOne extends React.Component { constructor(props) { super(props); this.state = { classtwo: new ClassTwo(), }; } CallGetValue(){ this.state.classtwo.getValue(); } } class ClassTwo extends React.Component { constructor(props) { super(props); this.state = { value: 100, }; } getValue(){ return this.state.value; } }