【问题标题】:Export function from React Class从 React 类导出函数
【发布时间】:2020-03-06 05:10:30
【问题描述】:

我正在尝试使用 react js 实现一个 dapp。在我的 app.js 应用程序类中,有一个我想导出到另一个模块的方法。我尝试了很多选项,但没有一个对我有用。在下面的代码中,我想导出用户名()。

App.js 代码

export default class SessionStore 
{ 
......  
username () 
    {
    if (!this._user || !this._user.username) return null
    return this._user.username   
    } 
......
}

如何将 username() 函数导入和使用到其他模块。我是 reactjs 新手,所以请帮我解决这个问题。

【问题讨论】:

  • 在你的函数前添加一个static,并将其用作SessionStore.usename()
  • @Veena S 您是否尝试在其他反应组件中使用该方法?

标签: javascript reactjs blockchain ethereum


【解决方案1】:

您可以将方法设为静态,但不能访问方法中的道具或状态。最好写一个 util 函数,它接受用户作为参数并在两个类中导入。

utils.js

export const getUserName = (user = {}) => user.username ? user.username : null;

App.js

import { getUserName } from '../utils';

export default class SessionStore { 
......  
  username = () => getUserName(this._user);
......
}

【讨论】:

    猜你喜欢
    • 2019-04-10
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多