【问题标题】:Reactjs undefined context in function called by child子调用的函数中的Reactjs未定义上下文
【发布时间】:2015-09-18 08:23:35
【问题描述】:

我对 ReactJS 和 Material UI 还是很陌生。我正在尝试在孩子的 onItemTap 事件调用的方法中使用我的 LeftList ES6 类的上下文。

class LeftList extends React.Component {
  constructor(props, context) {
    super(props, context);
    console.log('constructor:');
    console.log(context);
    this.state = { menuItems: [] };
  }

  render() {
    return (
      <div>
        <Menu
            ref="menuItems"
            zDepth={0}
            menuItems={this.state.menuItems}
            onItemTap={this.onMenuItemClick} />
      </div>
    );
  }

  onMenuItemClick(e, index, item) {
    console.log('onMenuItemClick:');
    console.log(this.context);
  }
}

LeftList.contextTypes = {
    router: React.PropTypes.func
};

Console output(很抱歉我无法将图片直接粘贴到帖子中)

如您所见,在构造函数中定义了上下文,但在onItemTap调用的方法内部是未定义的。

你知道是什么问题吗?

据我所知,Material UI 文档应用程序使用几乎相同的解决方案(在PageWithNav 类中),但是它们没有使用 ES6 类。

【问题讨论】:

标签: javascript reactjs react-router


【解决方案1】:

我设法解决了这个问题。 onMenuItemClick 方法中的this 关键字指的是Menu,即从LeftList 类调用,而不是从LeftList 类调用。所以我将上下文作为参数传递给Menu

<Menu
    ref="menuItems"
    zDepth={0}
    menuItems={this.state.menuItems}
    onItemTap={this.onMenuItemClick}
    context={this.context} />

非常感谢您的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多