0

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);
FeelRightz
  • 2,777
  • 2
  • 38
  • 73
  • You are trying to call a `static` method `B.SetContent();` rather, you should find a way to get an instance of `B` and call the method over the instance. – Panther Oct 19 '17 at 09:10

2 Answers2

3

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

  • any example i can refer to ? I very new and not familiar in Redux, just read some redux docs, feeling confuse. – FeelRightz Oct 19 '17 at 08:55
  • How did you start using react? Getting started from a starter kit is better as you won't have to configure everything yourself at first. you can go to the link I posted, and work your way up, if you get stuck, comment again, and I'll show you step by step on how to configure. –  Oct 19 '17 at 09:07
  • I start from react navigation – FeelRightz Oct 20 '17 at 02:34
1

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

arikanmstf
  • 462
  • 7
  • 16