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

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绑定事件的方式:

  1. 在元素中直接bind绑定方法,但是每次render的时候都会触发到函数

  2. 在元素中使用箭头函数,这样子可以传参,但是会发现这样子只不过是把相同的函数放到不同的内存里面


holdtom
浏览 930回答 4
4回答

凤凰求蛊

嗨,如果不希望用匿名函数的话,可以将 img 抽象一层组件,供参考:class AlbumItem extends React.PureComponent {&nbsp; onClick = () => this.props.onClick && this.props.onClick(this.props.song)&nbsp; render () {&nbsp; &nbsp; const { song, onClick, ...restProps } = this.props&nbsp; &nbsp; return <img {...restProps} onClick={this.onClick} />&nbsp; }}

森栏

你不知道bind函数可以有多个参数吗,另外在构造函数里传递参数似乎没有什么意义
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript