https://codesandbox.io/s/k0q179orqv我正在尝试做的事情:创建一个onclick事件和处理程序以开始gsap动画。换句话说,处理程序要做的就是:beginAnimation (){ this.tl.play()}我想做的是:首先在About.js中添加一个引用,然后将其转发到Card.js,并且在我希望能够单击以开始动画的箭头上。引用在对象中向下传递,并像这样“ 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} />但是我收到一个错误:TypeError:无法读取未定义的属性“ tl”我很新来做出反应,裁判出于某种原因使我的生活困惑
1 回答

慕码人8056858
TA贡献1803条经验 获得超6个赞
当您将一个函数传递给另一个组件时,this
是指调用该函数的组件(子组件),而不是“拥有”该函数的组件。
您可以解决这两种方法,要么将prop包裹在箭头函数周围,以封装this
父组件的值:
onClick={() => props.beginAnimation()}
或将this
值绑定到构造函数中的函数:
this.beginAnimation = this.beginAnimation.bind(this)
添加回答
举报
0/150
提交
取消