反应动态事件 [英] React dynamic events

查看:80
本文介绍了反应动态事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难将动态事件附加到我的反应组件上。我有以下组件:

I have difficulties to attach dynamic events to my react components. I have the following components:

var ListItem = React.createClass({
    render: function() {
        return (
            <li className="selector" >
                <div className="column">
                    <h2 className="commentAuthor">
                        {this.props.author}
                    </h2>
                    <div>{this.props.children}</div>
                </div>
            </li>
        );
    }
});

var ListBox = React.createClass({
    mixins : [MyMixin],

    render : function() {
        this.nodes = this.props.data.map(function(item) {
            return <ListItem author={item.author}>{item.text}</ListItem>;
        });
        return (
            <ul id="columns">
                {this.nodes}
            </ul>
        );
    }
});

如您所见,ListItem的className设置为selector。基于这个选择器,我想查询节点并在MyMixin中动态附加事件。

As you see the ListItem has className set to "selector". Base on this "selector" I want to query nodes and attach dynamically events in the MyMixin.

React.renderComponent(
    <ListBox data={data} selector="li.selector" />,
    document.getElementById('example')
);

也许我的想法完全错了,因为我对React不熟悉。

Maybe my idea is all wrong as I'm fairy new to React.

问候

推荐答案

你应该直接在ListItem上听事件零件。 React不希望你考虑以后附加监听器。

You should listen to events directly on the ListItem component. React doesn't want you to think about attaching listeners later.

var ListItem = React.createClass({
    handleClick: function(event) {
      // Handle ListItem click
    },
    handleDoubleClick: function(event) {
      // Handle ListItem double click
    },
    render: function() {
        return (
            <li className="selector"
                    onClick={this.handleClick}
                    onDoubleClick={this.handleDoubleClick}>
                <div className="column">
                    <h2 className="commentAuthor">
                        {this.props.author}
                    </h2>
                    <div>{this.props.children}</div>
                </div>
            </li>
        );
    }
});

React期望属性与事件名称完全匹配。您可以查看支持的活动的完整列表以确保你使用正确的名字。

React expects the attributes to exactly match the event name. You can check out the full list of supported events to make sure you use the right names.

这篇关于反应动态事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆