为了账号安全,请及时绑定邮箱和手机立即绑定

React 构造函数绑定事件如何传参

React 构造函数绑定事件如何传参

holdtom 2019-03-14 14:15:24
class albumList extends PureComponent {    constructor(props) {        super(props)        this.play = this.play.bind(this)    }    play(song) {        console.log(song)    }    render() {        return(            <div className="album-list">                {                    this.props.data.map((item,index)=>{                        return (                            <div className="album-list-item" key={index}>                                    <img onClick={this.play } alt="" src="./img/album-list-play.png" />                            </div>                        )                    })                }            </div>        );    }}上面的代码中,事件 play 在构造函数中使用bind的方式绑定,但是发现好像穿不了参数,在构造函数中绑定事件这样的方式是react中比较推荐的优化方案,而又想传参的话,该怎么写呢?react绑定事件的方式:在元素中直接bind绑定方法,但是每次render的时候都会触发到函数在元素中使用箭头函数,这样子可以传参,但是会发现这样子只不过是把相同的函数放到不同的内存里面
查看完整描述

4 回答

?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

嗨,如果不希望用匿名函数的话,可以将 img 抽象一层组件,供参考:


class AlbumItem extends React.PureComponent {

  onClick = () => this.props.onClick && this.props.onClick(this.props.song)

  render () {

    const { song, onClick, ...restProps } = this.props

    return <img {...restProps} onClick={this.onClick} />

  }

}


查看完整回答
反对 回复 2019-04-04
?
森栏

TA贡献1810条经验 获得超5个赞

你不知道bind函数可以有多个参数吗,另外在构造函数里传递参数似乎没有什么意义


查看完整回答
反对 回复 2019-04-04
  • 4 回答
  • 0 关注
  • 928 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信