簡體   English   中英

使用param調用函數時出現錯誤

[英]I got the error when calling a function with param

onTypeSelect (str) {
        this.setState({taskType: str})
    }

<TouchableOpacity onPress={this.onTypeSelect('type1').bind(this)}>
</TouchableOpacity>

undefined不是對象(評估'_this3.onTypeSelect('type1).bind')。

誰能幫我? 我是react-native的初學者。

嘗試這個

onTypeSelect (str) {
    this.setState({taskType: str})
}

<TouchableOpacity onPress={() => { this.onTypeSelect('type1'); }} />

.bind(this)時, 您需要傳遞一個函數而不是函數的返回值,在這種情況下為undefined 這樣,它的工作原理,因為函數是由從而使組件范圍內叫this有效的參考。

解決該問題的另一種方法是使用這種方式的綁定:

this.onTypeSelect.bind(this, 'type1')

編輯:感謝您的評論和其他答復,我添加信息是為了完整起見和提供信息。 亞歷山大·T· 巴爾特F

基於.bind docs,您必須像這樣將參數傳遞給.bind

this.onTypeSelect.bind(this, 'type1')

fun.bind(thisArg[, arg1[, arg2[, ...]]])

在您的示例中,您調用方法

this.onTypeSelect('type1')

該方法返回結果 (在這種情況下, 結果將是undefined ),並且您嘗試將.bind應用於結果undefined

undefined.bind(this)

但是.bind僅存在於Function對象中,這就是為什么出現錯誤的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM