本文介绍了为什么我的onClick被调用渲染? - React.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我创建的组件:

I have a component that I have created:

class Create extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    var playlistDOM = this.renderPlaylists(this.props.playlists);
    return (
      <div>
        {playlistDOM}
      </div>
    )
  }

  activatePlaylist(playlistId) {
    debugger;
  }

  renderPlaylists(playlists) {
    return playlists.map(playlist => {
      return <div key={playlist.playlist_id} onClick={this.activatePlaylist(playlist.playlist_id)}>{playlist.playlist_name}</div>
    });
  }
}

function mapStateToProps(state) {
  return {
    playlists: state.playlists
  }
}

export default connect(mapStateToProps)(Create);

当我渲染此页面时,<$在我的地图中为每个播放列表调用c $ c> activatePlaylist 。如果我 bind activatePlaylist 喜欢:

When I render this page, activatePlaylist is called for each playlist in my map. If I bind activatePlaylist like:

activatePlaylist.bind(this, playlist.playlist_id)

我也可以使用匿名函数:

I can also use an anonymous function:

onClick={() => this.activatePlaylist(playlist.playlist_id)}

然后按预期工作。为什么会发生这种情况?

then it works as expected. Why does this happen?

推荐答案

您需要传递给 onClick 参考来运行,当你这样做 activatePlaylist(..)你调用函数并传递给 onClick activatePlaylist 返回的值。您可以使用以下三个选项之一:

You need pass to onClick reference to function, when you do like this activatePlaylist( .. ) you call function and pass to onClick value that returned from activatePlaylist. You can use one of these three options:

1 。使用 .bind

activatePlaylist.bind(this, playlist.playlist_id)

2 。使用箭头功能

onClick={ () => this.activatePlaylist(playlist.playlist_id) }

3 。或从 activatePlaylist返回函数

activatePlaylist(playlistId) {
  return function () {
     // you code
  }
}

这篇关于为什么我的onClick被调用渲染? - React.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-30 00:30