Reputation: 2999
I would like to setState
from A
component to B
component. A
and B
are different JS file. I have tried to import B
to A
and access the function inside B
. Also have make the function in B
to static, then only find out static function no have instance, so I could not access this
in static.
A.js
import B from '../B';
class A extends React.Component {
ChangeBContent(){
B.SetContent();
}
render(){
return(
<View>
<SpeicalBtn onPress={()=> this.ChangeBContent()}/>
</View>
);
}
}
module.exports = A;
AppRegistry.registerComponent('myApp', () => A);
B.js
class B extends React.Component {
constructor(props) {
super(props);
this.state = {
content:''
}
}
SetContent(){
this.setState({content:'123'});
}
render(){
return(
<View>
<Text>{this.state.content}</Text>
</View>
);
}
}
module.exports = B;
AppRegistry.registerComponent('myApp', () => B);
Upvotes: 0
Views: 2398
Reputation:
You can do dirty tricks but I think you'll need more cleaner approach.
This is where you'd use state management library such as redux there you have one global store, and you dispatch actions. You can look into this stackoverflow post
Upvotes: 3
Reputation: 473
You should wrap them into another container component.
ContentC.js
class ContentC extends React.Component {
constructor(props) {
super(props);
this.state = {
contentA:'',
contentB: ''
}
}
SetContentA(){
this.setState({contentA:'123'});
}
SetContentB(){
this.setState({contentB:'123'});
}
render(){
return(
<ClassA content={this.state.contentA} />
<ClassB content={this.state.contentB}/>
);
}
}
And now you can use content with props.contentA
and props.contentB
Upvotes: 1