【问题标题】:React Native: Run method between two separate classReact Native:两个单独的类之间的运行方法
【发布时间】:2023-03-29 02:02:01
【问题描述】:

如何在 React Native 中的两个独立类之间运行方法。

例如:

头等舱

export default class Test1 extends Component {

    testMethod(){
        // ...
    }

    render() {
        ...
    }
}

二等舱

export default class Test2 extends Component {

    componentWillMount(){
        Test1.testMethod();
    }

    render() {
    ...
    }
}

【问题讨论】:

标签: react-native


【解决方案1】:

你的 testMethod 应该在类之外,如下所示

export const testMethod = () => {
        // ...
}

export default class Test1 extends Component {

    render() {
        ...
    }
}

如果你想修改类Test1的对象属性,你可以将它们作为testMethod()的参数传递,并且更改将被重新执行

【讨论】:

    【解决方案2】:

    这是一个简单的方法......

    export default class CommonDataManager {
    
        static myInstance = null;
    
        _userID = "";
    
    
        /**
         * @returns {CommonDataManager}
         */
        static getInstance() {
            if (CommonDataManager.myInstance == null) {
                CommonDataManager.myInstance = new CommonDataManager();
            }
    
            return this.myInstance;
        }
    
        getUserID() {
            return this._userID;
        }
    
        setUserID(id) {
            this._userID = id;
        }
    }
    

    这里是如何使用它...

    import CommonDataManager from './CommonDataManager';
    
    
    // When storing data.
    let commonData = CommonDataManager.getInstance();
    commonData.setUserID("User1");
    
    
    // When retrieving stored data.
    let commonData = CommonDataManager.getInstance();
    let userId = commonData.getUserID();
    console.log(userId);
    

    希望这对你有用:)

    【讨论】:

      猜你喜欢
      • 2016-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-29
      相关资源
      最近更新 更多