在 ref 上创建点击事件

Creating an on click event on ref

https://codesandbox.io/s/k0q179orqv

我想做什么:
创建一个 onclick 事件和处理程序来开始 gsap 动画。换句话说,所有处理程序将做的是:

beginAnimation (){
  this.tl.play()
}

我尝试过的事情: 我首先在 About.js 中添加了一个 ref,它被转发到 Card.js 并且位于我希望能够单击以开始动画的箭头上。 refs 在对象中向下传递,并像这样访问 "ref.ref2"

我试过这样做:

在About.js中创建一个方法:

  beginAnimation() {
    this.tl.play();
  }

并将其传递给正在渲染的卡片:

 createCards(card, i) {
    return (
      <Card
        id={i}
        key={i}
        card={card}
        info={this.state.aboutCards}
        ref={{ ref1: this["card" + i], ref2: this.button }}
        beginAnimation={this.beginAnimation}
      />
    );
  }
}

然后在 Card.js:

      <div className="prevnext">
        <button
          className="pn-btn"
          id="prev"
          ref={ref.ref2}
          onClick={props.beginAnimation}
        />

但我收到一个错误: 类型错误:无法读取未定义的 属性 'tl'

我对反应很陌生,出于某种原因,裁判让我感到困惑

当您将函数传递给另一个组件时,this 指的是调用它的组件(子组件),而不是 "owns" 该函数的组件。

你可以通过两种方式解决这个问题,要么将你的 prop 包裹在箭头函数周围以封装父组件的 this 值:

onClick={() => props.beginAnimation()}

或者将this值绑定到构造函数中的函数:

this.beginAnimation = this.beginAnimation.bind(this)