简体   繁体   English

React Native-不同JS文件之间的setState

[英]React Native - setState between different JS file

I would like to setState from A component to B component. 我想setStateA组件到B组件。 A and B are different JS file. AB是不同的JS文件。 I have tried to import B to A and access the function inside B . 我试图将B导入A并访问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. 也使B的函数变为静态,然后仅找出静态函数没有实例,因此我无法以静态方式访问this

A.js 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 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. 在这里,您将使用状态管理库(例如redux),那里有一个全局存储,并调度动作。 You can look into this stackoverflow post 您可以查看此stackoverflow 帖子

You should wrap them into another container component. 您应该将它们包装到另一个容器组件中。

ContentC.js 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 现在,您可以将内容与props.contentAprops.contentB

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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