Skip to main content

安装使用

安装

原生

# 安装主体
pnpm i gsap

# 安装插件
pnpm install gsap-trial

react

pnpm i gsap @gsap/react

引入使用

https://gsap.com/docs/v3/Installation?tab=npm&module=esm&method=private+registry&tier=free&club=true&require=false&trial=true&plugins=ScrollTrigger

官方案例

import { useRef } from 'react';
import gsap from 'gsap';
import { useGSAP } from '@gsap/react';

// 注册useGSAP
gsap.registerPlugin(useGSAP);

const { useRef } = React;
console.log(React.version);

function App() {
const container = useRef();
const circle = useRef();
useGSAP(
(context, contextSafe) => {
// use selectors...
gsap.to(".box", { rotation: "+=360", duration: 3 });

// or refs...
gsap.to(circle.current, { rotation: "-=360", duration: 3 });

// 事件创建需要使用contextSafe包裹,否则不会按照预期执行
const onCircleClick = contextSafe(() => {
gsap.to(goodRef.current, { rotation: 180 });
});

// 事件绑定
circle.current.addEventListener('click', onCircleClick)

// 事件移除
return () => {
circle.current.removeEventListener('click', onCircleClick);
};
},
{ scope: container }
); // <-- scope for selector text (optional)

return (
<div className="App">
<div ref={container} className="container">
<div className="box gradient-blue">selector</div>
<div className="circle gradient-green" ref={circle}>
Ref
</div>
</div>
<div className="box gradient-blue">selector</div>
</div>
);
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);

事件绑定

function App() {
const { contextSafe } = useGSAP();

// ✅ wrapped in contextSafe() - animation will be cleaned up correctly
const onEnter = contextSafe(({ currentTarget }) => {
gsap.to(currentTarget, { rotation: "+=360" });
});

return (
<div className="app flex-row">
<div className="box gradient-blue" onClick={onEnter}>
Click Me
</div>
</div>
);
}