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

鍍金池/ 問答/HTML/ React事件監(jiān)聽時的傳參, bind or 閉包?

React事件監(jiān)聽時的傳參, bind or 閉包?

1.bind傳參

handleClick=(arg1, e)=>{};
使用時: onClick={this.handleClick.bind(this, "xxxx")

2.閉包傳參

handleClick=(arg1)=>{
return (e)=>{};
}; 
使用時: onClick={this.handleClick("xxxx")}

有時候事件監(jiān)聽, 需要傳遞一些參數(shù), 這兩種方法那種方法更好一些? 或者哪種有弊端? 第二種 在組件銷毀時 ,閉包會銷毀么?

回答
編輯回答
遺莣

如何正確地在React中處理事件

參考官網(wǎng)

1、構(gòu)造器內(nèi)綁定this

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0
        };
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        this.setState({
            count: ++this.state.count
        });
    }

    render() {
        return (
        <div>
            <div>{this.state.count}</div>
            <button onClick={this.handleClick}>Click</button>
        </div>
        );
    }
}

這種方式的好處是每次render,不會重新創(chuàng)建一個回調(diào)函數(shù),沒有額外的性能損失。需要注意的是,使用這種方式要在構(gòu)造函數(shù)中為事件回調(diào)函數(shù)綁定this: this.handleClick = this.handleClick.bind(this),否則handleClick中的this是undefined。這是因為ES6 語法的緣故,ES6 的 Class 構(gòu)造出來的對象上的方法默認(rèn)不綁定到 this 上,需要我們手動綁定。

2、屬性初始化

使用ES7的 property initializers,代碼可以這樣寫:

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0
        };
    }

    handleClick = () => {
        this.setState({
            count: ++this.state.count
        });
    }

    render() {
        return (
        <div>
            <div>{this.state.count}</div>
            <button onClick={this.handleClick}>Click</button>
        </div>
        );
    }
}

這種方式就不需要手動綁定this了。但是你需要知道,這個特性還處于試驗階段,默認(rèn)是不支持的。如果你是使用官方腳手架Create React App 創(chuàng)建的應(yīng)用,那么這個特性是默認(rèn)支持的。你也可以自行在項目中引入babel的transform-class-properties插件獲取這個特性支持。

3、箭頭函數(shù)

class MyComponent extends React.Component {
    render() {
        return (
        <button onClick={()=>{console.log('button clicked');}}>
            Click
        </button>
        );
    }
}

當(dāng)事件響應(yīng)邏輯比較復(fù)雜時,如果再把所有的邏輯直接寫在onClick的大括號內(nèi),就會導(dǎo)致render函數(shù)變得臃腫,不容易直觀地看出組件render出的元素結(jié)構(gòu)。這時,可以把邏輯封裝成組件的一個方法,然后在箭頭函數(shù)中調(diào)用這個方法。如下所示:

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0
        };
    }
    handleClick() {
        this.setState({
            count: ++this.state.count
        });
    }
    render() {
        return (
        <div>
            <div>{this.state.number}</div>
            <button onClick={()=>{this.handleClick();}}>Click</button>
        </div>
        );
    }
}

這種方式最大的問題是,每次render調(diào)用時,都會重新創(chuàng)建一個事件的回調(diào)函數(shù),帶來額外的性能開銷,當(dāng)組件的層級越低時,這種開銷就越大,因為任何一個上層組件的變化都可能會觸發(fā)這個組件的render方法。當(dāng)然,在大多數(shù)情況下,這點性能損失是可以不必在意的。這種方式也有一個好處,就是不需要考慮this的指向問題,因為這種寫法保證箭頭函數(shù)中的this指向的總是當(dāng)前組件。

4、函數(shù)傳遞參數(shù)

事件的回調(diào)函數(shù)默認(rèn)是會被傳入一個事件對象Event作為參數(shù)的。如果我想傳入其他參數(shù)給回調(diào)函數(shù)應(yīng)該怎么辦呢?

使用第一種方式(構(gòu)造器內(nèi)綁定this)的話,可以把綁定this的操作延遲到render中,在綁定this的同時,綁定額外的參數(shù):

// 代碼6
class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        list: [1,2,3,4],
        current: 1
        };
    }

    handleClick(item) {
        this.setState({
            current: item
        });
    }

    render() {
        return (
        <ul>
            {this.state.list.map(
                (item)=>(
                <li className={this.state.current === item ? 'current':''} 
                onClick={this.handleClick.bind(this, item)}>{item}
                </li>
                )
            )}
        </ul>
        );
    }
}

使用第二種方式(屬性初始化),解決方案和第一種基本一致:

// 代碼7
class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            list: [1,2,3,4],
            current: 1
        };
    }

    handleClick = (item) =>  {
        this.setState({
            current: item
        });
    }

    render() {
        return (
        <ul>
            {this.state.list.map(
                (item)=>(
                <li className={this.state.current === item ? 'current':''} 
                onClick={this.handleClick.bind(undefined, item)}>{item}
                </li>
                )
            )}
        </ul>
        );
    }
}

不過這種方式就有點雞肋了,因為雖然你不需要通過bind函數(shù)綁定this,但仍然要使用bind函數(shù)來綁定其他參數(shù)。

使用第三種方式(函數(shù)傳遞參數(shù))的話很簡單,直接傳就可以了:

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            list: [1,2,3,4],
            current: 1
        };
    }

    handleClick(item,event) {
        this.setState({
            current: item
        });
    }

    render() {
        return (
        <ul>
            {this.state.list.map(
                (item)=>(
                <li className={this.state.current === item ? 'current':''} 
                onClick={(event) => this.handleClick(item, event)}>{item}
                </li>
                )
            )}
        </ul>
        );
    }
}

關(guān)于事件響應(yīng)的回調(diào)函數(shù),還有一個地方需要注意。不管你在回調(diào)函數(shù)中有沒有顯式的聲明事件參數(shù)Event,React都會把事件Event作為參數(shù)傳遞給回調(diào)函數(shù),且參數(shù)Event的位置總是在其他自定義參數(shù)的后面。例如,在代碼6和代碼7中,handleClick的參數(shù)中雖然沒有聲明Event參數(shù),但你依然可以通過arguments[1]獲取到事件Event對象。

總結(jié)一下,三種綁定事件回調(diào)的方式,第一種有額外的性能損失;第二種需要手動綁定this,代碼量增多;第三種用到了ES7的特性,目前并非默認(rèn)支持,需要Babel插件的支持,但是寫法最為簡潔,也不需要手動綁定this。推薦使用第二種和第三種方式。

2017年9月14日 03:01
編輯回答
歆久

現(xiàn)在推薦的寫法是第二種方式,第一種方式在每次rerender的時候都會重新生成一個新的函數(shù)

2018年7月3日 04:33
編輯回答
情殺
<div onClick={(e)=>{this.handleClick(e,xxx)}></div>
2017年9月28日 01:14