Reactjs 不使用内联lambda的Typescript和React refs
以下TypeScript中的快速示例展示了一种不使用内联(这被认为对性能有害)而获取类型化引用的方法。然而,必须定义两个变量(Reactjs 不使用内联lambda的Typescript和React refs,reactjs,typescript,Reactjs,Typescript,以下TypeScript中的快速示例展示了一种不使用内联(这被认为对性能有害)而获取类型化引用的方法。然而,必须定义两个变量(refAnimationWrapper和refAnimationWrapperHandler)来定义一个ref是相当难看的。是否有人有一个更简单的解决方案,@decorators可能是一个解决方案 import*as React from'React'; 从“gsap”导入{TweenMax}; 导出类TransitionDummy扩展React.Component{
refAnimationWrapper
和refAnimationWrapperHandler
)来定义一个ref是相当难看的。是否有人有一个更简单的解决方案,@decorators可能是一个解决方案
import*as React from'React';
从“gsap”导入{TweenMax};
导出类TransitionDummy扩展React.Component{
私人过渡期=0.4;
私有重构包装器:htmldevelment;
私有refAnimationWrapperHandler=(ref:htmldevelment)=>this.refAnimationWrapper=ref;
建造师(道具){
超级(道具);
}
公共组件将输入(完成){
TweenMax.fromTo(this.refAnimationWrapper,this.transitionDuration,{opacity:0},{opacity:1,onComplete:done});
}
公共组件将离开(完成){
to(this.refAnimationWrapper,this.transitionDuration,{opacity:0,onComplete:done});
}
公共渲染(){
返回(
{this.props.children}
);
}
}
您可以将它们都包装在一个类中,这样每个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>
);
}
}
类引用元素{
包装:T;
handler=(ref:T)=>this.wrapper=ref;
}
导出类TransitionDummy扩展React.Component{
私人过渡期=0.4;
私有重构:RefedElement;
建造师(道具){
超级(道具);
this.refAnimation=new RefedElement();
}
公共组件将输入(完成){
TweenMax.fromTo(this.refAnimation.wrapper,this.transitionDuration,{opacity:0},{opacity:1,onComplete:done});
}
公共组件将离开(完成){
to(this.refAnimation.wrapper,this.transitionDuration,{opacity:0,onComplete:done});
}
公共渲染(){
返回(
{this.props.children}
);
}
}
为什么做this.refAnimationWrapper=input}>
的性能比
差?哦,没关系,我看到人们在谈论它。就我个人而言,我不会为了节省几微秒而牺牲代码质量。我只是使用内联lambdas@DavidSherret我可能最终会采用这种方法,我只是想知道是否有一种方法可以同时获得这两种方法。但可能对性能的影响很小。@basarat是的,这正是我试图避免的。如果此代码为您编译,我得到:Error:(21,9)TS2322:类型“RefedElement”不可分配给类型“RefedElement”。类型“{}”不可分配给类型“HtmlLevel”。类型“{}”中缺少属性“align”。
我也不认为这段代码可以节省太多的键入,除非我们可以将新的RefedElement()调用直接移动到变量定义。对,它应该是new RefedElement()
,在答案中已修复。而且,当您有多个“RefedElement”时,它确实可以节省代码量。