React - Attaching click handler to dynamic children

给你一囗甜甜゛ 提交于 2019-12-11 04:36:14

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/31528079/react-attaching-click-handler-to-dynamic-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!