在this tutorial之后,我正在尝试使用打字稿来实现类似的组件。
我的组件:
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
)。
答案 0 :(得分:0)
您目前没有在ChaptersList
中进行任何操作来设置this.container
,因此el
将是未定义的。这应该通过最外面的ref
上的div
处理。
render
中的ChaptersList
应该如下:
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>
);
}