问题描述
我创建了一个组件:
类创建扩展组件{构造函数(道具){超级(道具);}使成为() {var playlistDOM = this.renderPlaylists(this.props.playlists);返回 ({播放列表DOM}</div>)}激活播放列表(播放列表 ID){调试器;}渲染播放列表(播放列表){返回播放列表.map(播放列表 => {return <div key={playlist.playlist_id} onClick={this.activatePlaylist(playlist.playlist_id)}>{playlist.playlist_name}</div>});}}功能 mapStateToProps(状态){返回 {播放列表:state.playlists}}导出默认连接(mapStateToProps)(创建);当我 render
这个页面时,activatePlaylist
会为我的 map
中的每个 playlist
调用.如果我 bind
activatePlaylist
喜欢:
activatePlaylist.bind(this, playlist.playlist_id)
我也可以使用匿名函数:
onClick={() =>this.activatePlaylist(playlist.playlist_id)}
然后它按预期工作.为什么会这样?
解决方案 你需要传递给 onClick
reference 才能起作用,当你这样做 activatePlaylist(..)
您调用函数并传递给从 activatePlaylist
返回的 onClick
值.您可以使用以下三个选项之一:
1.使用 .bind
activatePlaylist.bind(this, playlist.playlist_id)
2.使用箭头函数
onClick={ () =>this.activatePlaylist(playlist.playlist_id) }
3.或从 activatePlaylist
返回函数activatePlaylist(playlistId) {返回函数(){//你编码}}
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);
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?
解决方案 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. using .bind
activatePlaylist.bind(this, playlist.playlist_id)
2. using arrow function
onClick={ () => this.activatePlaylist(playlist.playlist_id) }
3. or return function from activatePlaylist
activatePlaylist(playlistId) {
return function () {
// you code
}
}
这篇关于为什么我的 onClick 在渲染时被调用?- React.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
05-17 17:48