【发布时间】:2015-01-20 15:51:17
【问题描述】:
我可以将我的事件处理程序附加到一个 React 组件。有没有办法在事件处理程序中获取对该组件的引用?
var Foobar = React.createClass({
action: function () {
// ...
},
render: function () {
var child = React.Children.only(this.props.children),
props = _.omit(this.props, 'children');
return React.addons.cloneWithProps(child, props);
}
});
var App = React.createClass({
handleMouseEnter: function (event) {
// How to get reference to Foobar without using this.refs['foo']?
// I need to call *action* on it.
},
render: function () {
return (
<div>
<Foobar ref="foo" onMouseEnter={this.handleMouseEnter}>
...
</Foobar>
</div>
);
}
});
【问题讨论】:
-
为什么不在
Foobar组件内部定义handleMouseEnter并通过this访问呢? -
@daniula 因为
Foobar.action方法可能由于onClick事件而被调用,而不仅仅是onMouseEnter。 -
action应该在 Foobar 实例上定义。this.refs.foo.action()不适合你吗? -
你能给出一些触发 onClick 的上下文吗?这会是一个带有 onClick 处理程序的反应组件,还是您指的是 React 映射到 App 组件中的处理程序之外的东西?
-
我不明白。如果
this.refs.foo有效,你为什么不想这样做?
标签: reactjs