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

在发送给子组件的回调中找不到父级的道具

  •  1
  • khateeb  · 技术社区  · 7 年前

    answer . 在我的回电中,我需要 props navigate 道具。但是 this.props 在回调返回中 undefined . 如何获得道具对象?我不想把导航道具传给孩子。

    回拨:

      _onSeperatorPress(item){
        console.log(item);
        console.log(this);
        this.navigation.navigate("main");
      }
    

    父调用子:

        <HorizontalList
          data={genresData}
          keyExtractor={(item, index) => item.description}
          onPress={this._onSeperatorPress} />
    

    子调用回调:

    <TouchableHighlight
                onPress={() => this.props.onPress(item)}
                onShowUnderlay={separators.highlight}
                onHideUnderlay={separators.unhighlight}>
                </TouchableHighlight>
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Hemadri Dasari    7 年前

    你有约束力的问题。为了访问函数中的状态或道具,需要绑定函数。

    ES5:普通函数,您需要在构造函数中手动绑定它

    this.handleFunction = this.handleFunction.bind(this);
    
    handleFunction(){
       console.log(this.props); // props are available
    }
    

    ES6:Arrow函数-绑定自动执行,您可以避开与范围相关的问题

    handleFunction = () = {
      console.log(this.props); // props are available 
    }
    
    推荐文章