Reactjs學習記錄(003)

var foo = {   

  x: 3 

  var bar = function(){     

console.log(this.x); 

 bar(); // undefined  

var boundFunc = bar.bind(foo);

boundFunc(); // 3

我們創建了一個新的函數,在執行時,它的this設置爲foo- 而不是全局範圍,就像我們調用的例子bar();

向事件處理程序傳遞參數

通常我們會爲事件處理程序傳遞額外的參數。例如,若是 id 是你要刪除那一行的 id,以下兩種方式都可以向事件處理程序傳遞參數:

<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

上述兩種方式是等價的,分別通過 arrow functions 和 Function.prototype.bind 來爲事件處理函數傳遞參數

上面兩個例子中,參數 e 作爲 React 事件對象將會被作爲第二個參數進行傳遞。通過箭頭函數的方式,事件對象必須顯式的進行傳遞,但是通過 bind 的方式,事件對象以及更多的參數將會被隱式的進行傳遞。


值得注意的是,通過 bind 方式向監聽函數傳參,在類組件中定義的監聽函數,事件對象 e 要排在所傳遞參數的後面,例如:

class Popper extends React.Component{
    constructor(){
        super();
        this.state = {name:'Hello world!'};
    }
    
    preventPop(name, e){    //事件對象e要放在最後
        e.preventDefault();
        alert(name);
    }
    
    render(){
        return (
            <div>
                <p>hello</p>
                {/* Pass params via bind() method. */}
                <a href="https://reactjs.org" onClick={this.preventPop.bind(this,this.state.name)}>Click</a>
            </div>
        );
    }
}

條件渲染

在 React 中,你可以創建不同的組件來封裝各種你需要的行爲。然後還可以根據應用的狀態變化只渲染其中的一部分。(由於對象的屬性可以賦給另一個對象,所以屬性所在的當前對象是可變的,即this的指向是可變的,

// class MyDate extends Date {
// constructor() {
// super();
// }

// getFormattedDate() {
// var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
// 'Oct', 'Nov', 'Dec'];
// return this.getDate() + '-' + months[this.getMonth()] + '-' +
// this.getFullYear();
// }
// }
)
// var aDate = new MyDate();
// console.log(aDate.getTime());
// console.log(aDate.getFormattedDate());

這裏已經清楚了說明了,箭頭函數沒有自己的 this 綁定。箭頭函數中使用的 this,其實是直接包含它的那個函數或函數表達式中的 this。比如const obj = {
    test() {
        const arrow = () => {
            // 這裏的 this 是 test() 中的 this,
            // 由 test() 的調用方式決定
            console.log(this === obj);
        };
        arrow();
    },


    getArrow() {
        return () => {
            // 這裏的 this 是 getArrow() 中的 this,
            // 由 getArrow() 的調用方式決定
            console.log(this === obj);
        };
    }
};


obj.test();     // true


const arrow = obj.getArrow();
arrow();        // true

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章