问题描述
我创建了一个组件:
class 创建扩展组件 {构造函数(道具){超级(道具);}使成为() {var playlistDOM = this.renderPlaylists(this.props.playlists);返回 (<div>{播放列表域}
我创建了一个组件:
class 创建扩展组件 {构造函数(道具){超级(道具);}使成为() {var playlistDOM = this.renderPlaylists(this.props.playlists);返回 (<div>{播放列表域}
)}activatePlaylist(playlistId) {调试器;}渲染播放列表(播放列表){返回 playlists.map(playlist => {return <div key={playlist.playlist_id} onClick={this.activatePlaylist(playlist.playlist_id)}>{playlist.playlist_name}</div>});}}函数 mapStateToProps(state) {返回 {播放列表:state.playlists}}导出默认连接(mapStateToProps)(创建);
当我呈现
这个页面时,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 在渲染时被调用?- 反应.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!