在事件处理程序中获取对React组件的引用

vba*_*osh 38 reactjs

我可以将我的事件处理程序附加到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>
        );
    }
});
Run Code Online (Sandbox Code Playgroud)

小智 41

我想我理解vbarbarosh问的问题,或者至少我有一个类似的问题引导我发表这篇文章.因此,如果这不能回答原始问题,希望它可以帮助那些降落在这里的人.

在我的例子中,我有一个带有n个子节点的React组件,用于定义UI操作的配置选项.每个孩子都有一个不同的引用,用于标识输入所代表的配置选项,并且我希望能够直接访问引用,以便我可以调用在我的子组件上公开的方法.(我可以公开数据attrs并使用jQuery来提取,但这似乎有很多额外的箍和性能问题)

我的第一次尝试是这样的:

...
<Config ref="showDetails" onChange={this.handleChange} />
<Config ref="showAvatar" onChange={this.handleChange} />
...
Run Code Online (Sandbox Code Playgroud)

理想情况下,我想将所有更改事件绑定到单个处理程序,然后从调度事件的目标中提取ref.不幸的是,被派遣SyntheticEvent没有提供获得目标参考的方法,所以我不能直接打电话给this.ref[name].methodIWantToCall().

我找到的是React文档中的一篇文章,它引导我找到解决方案:

https://facebook.github.io/react/tips/communicate-between-components.html

我们可以做的是利用JavaScript绑定并传入其他参数.

...
<Config ref="showDetails" onChange={this.handleChange.bind(this, 'showDetails')} />
...
Run Code Online (Sandbox Code Playgroud)

现在在我的处理程序中,我获得了添加数据并可以访问我的参考:

handleChange: function(refName, event) {
  this.refs[refName].myMethodIWantToCall()
}
Run Code Online (Sandbox Code Playgroud)

诀窍在于绑定时,参数顺序会发生变化,第一个参数现在是传入的绑定值,事件现在是第二个参数.希望有所帮助!

  • 这是一个优雅的解决方案,但由于性能原因,它不鼓励.请参阅https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md (5认同)

tad*_*llo 5

您必须将处理程序传播到子组件的根元素,如下所示:

var Foobar = React.createClass({
    action: function (e) {
        this.props.onClick(this);
    },
    render: function () {
        return <div onClick={this.action}>{this.props.children}</div>;
    }
});

var App = React.createClass({
    handleMouseEnter: function (foobar) {
       console.log(foobar);
    },
    render: function () {
        return (
            <Foobar ref="foo" onClick={this.handleMouseEnter} />
        );
    }
});
Run Code Online (Sandbox Code Playgroud)