反应-将点击处理程序附加到动态子级 [英] React - Attaching click handler to dynamic children

查看:54
本文介绍了反应-将点击处理程序附加到动态子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在电子应用中显示一个使用react + flux的播放列表。
由于某种原因,我无法将点击处理程序附加到每个播放列表项。

I'm trying to display a playlist in my electron app which uses react+flux. For some reason I can not attach a click handler to each playlist item.

这是我的代码:

var Playlist = React.createClass({

    render: function() {
        var list = this.props.list;
        var playlist = [];

        for (var i = 0; i < list.length; ++i) {
            playlist.push(
                <PlaylistItem song={list[i]} key={i} />
            );
        }

        return (
            <ul className='playlist'>
                {playlist}
            </ul>
        )
    }

});

var PlaylistItem = React.createClass({

    _play: function() {
        console.log(this.props.song);
    },

    render: function() {
        var song = this.props.song;

        return (
            <li>
                <div className='playBtn'>
                    <i className='fa fa-play' onClick={this._play}>
                    </i>
                </div>
                <div className='info'>
                    <div className='artist'>{song.artist}</div>
                    <div className='title'>{song.title}</div>
                </div>
                <div className='rmBtn'>
                    <i className='fa fa-minus-circle'>
                    </i>
                </div>
                <div className='time'>{song.time}</div>
            </li>
        );
    }

});

我不明白为什么点击处理程序永远不会触发。我希望当我单击i元素时,会将歌曲对象放到控制台。

I don't understand why the click handler never fires. I'd expect that when clicking the i element i'd get the song object to the console.

谢谢。

编辑:我对此进行了一些试验,每次我从商店获取数据(甚至是伪数据)时,单击处理程序均不起作用。但是,如果我将伪数据移到根组件中,则单击处理程序可以正常工作。

I did some experimenting with this and everytime I get the data from a store (even fake data) the click handlers don't work. But if I move the fake data into the root component the click handlers work fine.

我已检查数组中的对象多次相同。

I have checked that the objects in the array are identical multiple times.

我不明白为什么会这样。

I don't understand why this behaviour is happening.

任何人?

推荐答案

您需要绑定onClick方法
onClick = {this._play.bind(this)}

You need to bind the onClick method onClick={this._play.bind(this)}

这篇关于反应-将点击处理程序附加到动态子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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