TypeScript中的以下快速示例显示了一种在不使用内联的情况下获取类型化引用的方法(假设这对性能有害)。然而,必须定义两个变量(refAnimationWrapper
和refAnimationWrapperHandler
)以定义一个ref,这是相当丑陋的。有没有人有更简单的解决方案,@ decorators可能是一个解决方案吗?
https://www.typescriptlang.org/docs/handbook/decorators.html
import * as React from 'react';
import {TweenMax} from 'gsap';
export class TransitionDummy extends React.Component<any, any> {
private transitionDuration = 0.4;
private refAnimationWrapper:HTMLDivElement;
private refAnimationWrapperHandler = (ref:HTMLDivElement) => this.refAnimationWrapper = ref;
constructor(props) {
super(props);
}
public componentWillEnter(done) {
TweenMax.fromTo(this.refAnimationWrapper, this.transitionDuration, {opacity: 0}, {opacity: 1, onComplete: done});
}
public componentWillLeave(done) {
TweenMax.to(this.refAnimationWrapper, this.transitionDuration, {opacity: 0, onComplete: done});
}
public render() {
return (
<div ref={this.refAnimationWrapperHandler}>
{this.props.children}
</div>
);
}
}
答案 0 :(得分:2)
你可以将它们包装在一个类中,这样每个ref都有一个成员:
class RefedElement<T> {
wrapper: T;
handler = (ref: T) => this.wrapper = ref;
}
export class TransitionDummy extends React.Component<any, any> {
private transitionDuration = 0.4;
private refAnimation: RefedElement<HTMLDivElement>;
constructor(props) {
super(props);
this.refAnimation = new RefedElement<HTMLDivElement>();
}
public componentWillEnter(done) {
TweenMax.fromTo(this.refAnimation.wrapper, this.transitionDuration, {opacity: 0}, {opacity: 1, onComplete: done});
}
public componentWillLeave(done) {
TweenMax.to(this.refAnimation.wrapper, this.transitionDuration, {opacity: 0, onComplete: done});
}
public render() {
return (
<div ref={ this.refAnimation.handler }>
{this.props.children}
</div>
);
}
}