在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Android  HTML/ React 構造函數(shù)綁定事件如何傳參

React 構造函數(shù)綁定事件如何傳參

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 在構造函數(shù)中使用bind的方式綁定,但是發(fā)現(xiàn)好像穿不了參數(shù),在構造函數(shù)中綁定事件這樣的方式是react中比較推薦的優(yōu)化方案,而又想傳參的話,該怎么寫呢?

react綁定事件的方式:

  1. 在元素中直接bind綁定方法,但是每次render的時候都會觸發(fā)到函數(shù)
  2. 在元素中使用箭頭函數(shù),這樣子可以傳參,但是會發(fā)現(xiàn)這樣子只不過是把相同的函數(shù)放到不同的內存里面
回答
編輯回答
安若晴

constructor里的bind只是把該方法運行時的this綁定到組件實例上,調用方法不變。

所以參數(shù)是在調用的時候傳的,前面的bind相當于每次都這樣調用:

this.play.call(this, arguments)
2018年8月10日 10:04
編輯回答
不討喜

onClick的時候是會有event傳給你的


class albumList extends PureComponent {
    constructor(props) {
        super(props)
        this.play = this.play.bind(this)
    }
    play(e) {
        console.log(e.target.getAttribute('src'));
    }
    render() {
        return <img onClick={this.play } src="./img/album-list-play.png" />;
    }
}

一些id,name之類的參數(shù),也可以這樣傳遞


class albumList extends PureComponent {
    constructor(props) {
        super(props)
        this.play = this.play.bind(this)
    }
    play(e) {
        // data-前綴,只是一種規(guī)范,沒有實際意義
        console.log(e.target.getAttribute('data-id'));
    }
    render() {
        return <img
         onClick={this.play }
         src="./img/album-list-play.png"
         data-id={12}
       />;
    }
}

還有你的bind太麻煩了,尤其是比較復雜的組件,要一直.bind(this)。給你推薦一個裝飾器

import {autobind} from 'core-decorators';

class albumList extends PureComponent {
    @autobind
    play(e) {
      // play 已經(jīng)自動bind了
    }
    
    render() {
      return '一個插件';
    }
    
}

下載地址:
https://www.npmjs.com/package...

2017年8月15日 13:22
編輯回答
病癮

你不知道bind函數(shù)可以有多個參數(shù)嗎,另外在構造函數(shù)里傳遞參數(shù)似乎沒有什么意義

2017年7月2日 03:46
編輯回答
雨萌萌

嗨,如果不希望用匿名函數(shù)的話,可以將 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} />
  }
}
2018年1月29日 21:35