簡體   English   中英

將函數傳遞給子組件 react native

[英]pass a function to child component react native

我嘗試將 onChangeText() 傳遞給 react native 中的子組件,它起作用了:

onChangText(value){
    console.log(value)
}

render() {

    return (

        <View style={{flex:1}}>
            <Ui  
                onChangeText={this.onChangText()}  
            />
        </View>
    )
}

但是當我像下面這樣調用其他函數(在父函數中)時:

loger(value){
    console.log(value)
}
onChangText(value){
    this.loger(value)
}

render() {

    return (

        <View style={{flex:1}}>
            <Ui  
                onChangeText={this.onChangText()}
            />
        </View>  
    )
} 

我收到錯誤:this.loger 不是函數

在此處輸入圖片說明

你需要注意的兩件事

首先,在將函數傳遞給 child 時,您不需要調用它,只需像傳遞引用一樣

 <Ui  
      onChangeText={this.onChangText}
 />

其次,每當您需要在被調用的函數中使用this關鍵字時,您應該將函數綁定到正確的上下文。 在您的情況下,您需要將其綁定到父類的上下文,因此您可以為此使用箭頭函數

onChangText = (value) => {
    this.loger(value)
}

我通過在箭頭函數的主體中傳遞我的函數來解決這個問題,如下所示:

loger(value){
    console.log(value)
}
onChangeText(value){
    this.loger(value)
}

render() {

    return (
        <View style={{flex:1}}>
            <Ui 
                onChangeText={(value)=> this.onChangeText(value)}
            />
        </View>

    )
} 

暫無
暫無

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

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