溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

React中ref回調(diào)函數(shù)實(shí)現(xiàn)的方式有哪些

發(fā)布時間:2022-04-20 16:05:23 來源:億速云 閱讀:270 作者:iii 欄目:大數(shù)據(jù)

本文小編為大家詳細(xì)介紹“React中ref回調(diào)函數(shù)實(shí)現(xiàn)的方式有哪些”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“React中ref回調(diào)函數(shù)實(shí)現(xiàn)的方式有哪些”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識吧。

ES6回調(diào)函數(shù)

這里我們使用ES6回調(diào)函數(shù)實(shí)現(xiàn)獲取焦點(diǎn)

var MyComponent = React.createClass({
    handleClick: function() {
        // Explicitly focus the text input using the raw DOM API.
        if (this.myTextInput !== null) {
            this.myTextInput.focus();
        }
    },
    render: function() {
      return (
            <div>
                <input type="text" ref={ (ref)=>this.myTextInput = ref } />
                <input
                    type="button"
                    value="Focus the text input"
                    onClick={this.handleClick}
                    />
            </div>
        );
    }
});

CommonJs回調(diào)函數(shù)實(shí)現(xiàn)

var MyComponent = React.createClass({
    handleClick: function() {
        // Explicitly focus the text input using the raw DOM API.
        if (this.myTextInput !== null) {
            this.myTextInput.focus();
        }
    },
    render: function() {
      return (
            <div>
                <input type="text" ref={ function(ref){this.myTextInput = ref}.bind(this) } />
                <input
                    type="button"
                    value="Focus the text input"
                    onClick={this.handleClick}
                    />
            </div>
        );
    }
});

注意:在上面代碼中,使用的是CommonJs語法,回調(diào)函數(shù)function(){}后面有.bind(this)。這是需要注意的地方,綁定this,使function內(nèi)的this對象是該組件。如果不綁定this,那么在handleClick中的this.myTextInput將會報未定義的錯誤。這是需要注意的地方,在ES6中就不存在這個問題。

讀到這里,這篇“React中ref回調(diào)函數(shù)實(shí)現(xiàn)的方式有哪些”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點(diǎn)還需要大家自己動手實(shí)踐使用過才能領(lǐng)會,如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI