React - Attaching click handler to dynamic childre

2019-08-08 08:12发布

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.

Here's my code:

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 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.

Thanks.

Edit: 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.

Anyone?

2条回答
Viruses.
2楼-- · 2019-08-08 08:58

I have experienced this problem myself and resolved it as follows: https://stackoverflow.com/a/32623836/852872. Hope this helps for you too.

Answer from that page

I haven't done any deeper investigation why this didn't work for me, but the problem was that in my main file I imported React as require('React'), but on other components as require('React/addons'). After importing React everywhere from react/addons everything works as expected.

查看更多
乱世女痞
3楼-- · 2019-08-08 09:06

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

查看更多
登录 后发表回答