[英]gsap, react - Cannot tween a null target
在學習完本教程之后,我嘗試使用打字稿實現類似的組件。
我的組件:
import React, { Component } from "react";
import TransitionGroup from "react-addons-transition-group";
import { TweenMax } from "gsap";
import { tableOfContentsData } from "../mockData/tableOfContents";
import { Chapter } from "../types/data/tableOfContents";
import styled from "styled-components";
import { pallete } from "../constants/pallete";
type State = {
isExpanded: boolean;
};
const StyledContainer = styled.div`
position: fixed;
top: 0;
left: 0;
padding: 1em;
background-color: ${pallete.primary};
color: ${pallete.text};
font-size: 16px;
height: 100vh;
max-width: 200px;
.chapter-link {
min-height: 24px;
min-width: 54px;
margin-bottom: 1em;
}
.close-btn {
background-color: ${pallete.secondary};
position: absolute;
top: 0;
right: -54px;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
width: 54px;
}
`;
class TableOfContents extends Component<{}, State> {
state = {
isExpanded: true
};
toggleExpanded = (): void => {
this.setState({
isExpanded: !this.state.isExpanded
});
};
render() {
return (
<StyledContainer>
<TransitionGroup>
{this.state.isExpanded && <ChaptersList />}
</TransitionGroup>
<div className="close-btn" onClick={this.toggleExpanded}>
<
</div>
</StyledContainer>
);
}
}
class ChaptersList extends Component {
componentWillEnter(callback: any) {
const el = (this as any).container;
TweenMax.fromTo(
el,
0.3,
{ x: -100, opacity: 0 },
{ x: 0, opacity: 1, onComplete: callback }
);
}
componentWillLeave(callback: any) {
const el = (this as any).container;
TweenMax.fromTo(
el,
0.3,
{ x: 0, opacity: 1 },
{ x: -100, opacity: 0, onComplete: callback }
);
}
render() {
return (
<div>
{tableOfContentsData.map((chapter: Chapter, i: number) => (
<div key={i} className="chapter-link">
{chapter.title}
</div>
))}
</div>
);
}
}
export default TableOfContents;
當我單擊.close-btn
div時,出現以下錯誤:
未捕獲的異常:無法補間空目標。
我在谷歌搜索過程中發現的可能錯誤之一是TweenMax
導入,但是如果我嘗試從gsap/TweenMax
導入它,ts會抱怨缺少類型定義(我安裝了@types/gsap
)。
您目前沒有在ChaptersList
進行任何操作來設置this.container
,所以el
將是未定義的。 這應該通過最外層div
上的ref
處理。
ChaptersList
的render
應類似於:
render() {
return (
<div ref={c => (this as any).container = c}>{/* this is the change */}
{tableOfContentsData.map((chapter: Chapter, i: number) => (
<div key={i} className="chapter-link">
{chapter.title}
</div>
))}
</div>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.