简体   繁体   中英

React Native - setState between different JS file

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);

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM