代码之家  ›  专栏  ›  技术社区  ›  amirhosein

将函数传递给子组件react native

  •  -2
  • amirhosein  · 技术社区  · 6 年前

    我尝试将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>  
        )
    } 
    

    enter image description here

    2 回复  |  直到 6 年前
        1
  •  1
  •   Shubham Khatri    6 年前

    你需要注意两件事

    弗斯特

     <Ui  
          onChangeText={this.onChangText}
     />
    

    第二 ,无论何时需要使用 this 在被调用函数中,应该将函数绑定到正确的上下文。在您的例子中,您需要将它绑定到父类的上下文,因此可以使用arrow函数来实现这个目的

    onChangText = (value) => {
        this.loger(value)
    }
    
        2
  •  0
  •   amirhosein    6 年前

    我通过在箭头函数体中传递函数来解决这个问题,如下所示:

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