在子

时间:2015-09-18 08:23:36

标签: javascript reactjs react-router

我是ReactJS和Material UI的新手。我正在尝试在child的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 docs应用程序使用几乎相同的解决方案(在PageWithNav类中),但他们没有使用ES6类。

1 个答案:

答案 0 :(得分:0)

我设法解决了这个问题。 this方法中的onMenuItemClick关键字指的是Menu,它来自LeftList类,而不是Menu类。所以我将上下文作为参数传递给<Menu ref="menuItems" zDepth={0} menuItems={this.state.menuItems} onItemTap={this.onMenuItemClick} context={this.context} />

//defining your 'class', class in quotes since everything is just functions, objects, primitives, and the special null values in JS
var Foo = function (options) {
  // code in here will be ran when you call 'new', think of this as the constructor.

  //private function
  var doSomething = function () {
  }

  //public function
  this.doSomethingElse = function () {
  }
};

//actual instantiation of your object, the 'new' keyword runs the function and essentially returns 'this' within the function at the end
var foo = new Foo(
    {
      //options here
    }
)

非常感谢你的帮助。