我正在努力转换香草js gsap(GreenSock)动画以作出反应,并希望基于componentDidMount
(其中称为gsap补间)中的props访问值。动画基于https://codepen.io/zadvorsky/pen/dILAG,使用Delaunay三角剖分和补间动画使破碎的图像爆炸。如何访问所说的值?
最初,我在if(shatter)
内的render
中包含了计算,但是rx
,ry
和delay
的值在用于componentDidMount
。我将上述计算移至componentDidMount
,因此可以使用上述值,但即使使用constructor
,道具也无法使用。
export class Explosion extends React.Component {
constructor(props) {
super(props)
this.state = {
shatter: false
}
}
tl0 = new TimelineMax();
tl1 = new TimelineMax();
fragmentNode = React.createRef()
containerNode = React.createRef()
componentDidMount() {
if (this.state.shatter) {
const triangulatedValues = triangulate({
this.props.width,
this.props.height,
this.props.startX,
this.props.startY
})
const {
vertices,
indices
} = triangulatedValues
const ExplosionFragments = []
for (let i = 0; i < indices.length; i += 3) {
let point0 = vertices[indices[i + 0]]
let point1 = vertices[indices[i + 1]]
let point2 = vertices[indices[i + 2]]
let fragmentCentroid = computeCentroid({
point0,
point1,
point2
})
let dx = fragmentCentroid[0] - startX
let dy = fragmentCentroid[1] - startY
let d = Math.sqrt(dx * dx + dy * dy)
let rx = -30 * sign(dy)
let ry = -90 * -sign(dx)
let delay = d * 0.003 * randomRange(0.7, 1.1)
let box = computeBoundingBox({
point0,
point1,
point2
})
}
}
this.tl1
.to(this.fragmentNode, 1, {
z:500,
rotationX:rx,
rotationY:ry,
ease:Power2.easeInOut
})
.to(this.fragmentNode, 0.4,{alpha:0}, 1)
this.tl0
.insert(this.tl1, delay)
}
render() {
const {
shatter
} = this.state
return (
<Container
ref={this.containerNode}
onClick={this.handleToggleShatter}
>
{shatter ? (
<div>
<OverlayImage
src="http://i67.tinypic.com/2eq9utk.jpg"
/>
<canvas
width={width}
height={height}
ref={this.fragmentRef}>
</canvas>
</div>
) : (
<OverlayImage
src="http://i67.tinypic.com/2eq9utk.jpg"
/>
)}
</Container>
)
}
}
export default Explosion
https://codesandbox.io/s/ll139x3nx7
我希望道具在componentDidMount
中可用,但是会引发错误“解析错误:这是一个保留字”。对于可能的解决方案,这只是一个错误,我对任何前进的方向都持开放态度。
答案 0 :(得分:1)
当您这样做:
const triangulatedValues = triangulate({
this.props.width,
this.props.height,
this.props.startX,
this.props.startY
})
您要传入一个对象,其中键为this.props.width
等,并且值也为this.props.width
,因为您尚未指定任何其他键,因此它将尝试将键称为变量的名称。
尝试:
const triangulatedValues = triangulate({
width: this.props.width,
height: this.props.height,
startX: this.props.startX,
startY: this.props.startY
})