在 render() 块中引用父级的事件处理程序 [英] Referencing a parent's event handler within the render() block

查看:26
本文介绍了在 render() 块中引用父级的事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 onPress() 事件处理程序的子 Icon 元素:

I have a child Icon element with an onPress() event handler:

render() {
  return (
    <TouchableOpacity onPress={this.props.press}>
  )
}

这个孩子的 IconWrapper 父组件正在传递按下功能:

This child's IconWrapper parent component is passing down the press function with:

render() {
  return (
    <View>
      <Icon press={this.props.press} />
      <Icon press={this.props.press} />
      <Icon press={this.props.press} />
    </View>
  )
}

然后,我从祖父组件中渲染父 IconWrapper 组件:

Then, I'm rendering the parent IconWrapper component from the grandparent with:

render() {
  return (
    <View>
      <IconWrapper press={this.press} />
    </View>
  )
}

IconWrapper press 函数没有向下传播到 Icon.我相信我需要将此功能附加到外部 View 组件,然后使用 View 作为参考,例如:

The IconWrapper press function isn't propagating down to the Icon. I believe I need to attach this function to the outer View component, then use the View as a reference with something like:

render() {
  return (
    <View ref="outerView" press={this.props.press}>
      <Icon press={this.refs.outerView.press} />
      <Icon press={this.refs.outerView.press} />
      <Icon press={this.refs.outerView.press} />
    </View>
  )
}

或者也许:

render() {
  return (
    <View ref="outerView">
      <Icon press={this.refs.outerView.props.press} />
      <Icon press={this.refs.outerView.props.press} />
      <Icon press={this.refs.outerView.props.press} />
    </View>
  )
}

我将如何在 render() 块中引用父级的事件处理程序?

How would I go about referencing a parent's event handler within the render() block?

推荐答案

在您的 IconWrapper 中,将类的引用绑定到函数.这应该可以工作而无需使用 refs.

In your IconWrapper bind the reference of the class to the function. This should work without having to use refs.

render() {
  return (
    <View>
      <IconWrapper press={this.press.bind(this)} />
    </View>
  )
}

这篇关于在 render() 块中引用父级的事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆