[英]React - how to update state from the prop of other library
我正在使用react-scrollmagic
來實現滾動效果。
當我使用它的組件時,有一個叫做progress
的道具,
{(progress, event) => (
…
)}
我想通過它來更新我的 state currentProgress
。
我該怎么做?
應用程序.js
import "./styles.css";
import styled from "styled-components";
import { Controller, Scene } from "react-scrollmagic";
import React, { useState, useEffect } from "react";
const ClassToggleStyled = styled.div`
.section {
height: 100vh;
}
.test {
transition: width 0.3s ease-out;
width: 100px;
height: 100px;
background-color: red;
margin: 0 !important;
&.yellow {
background-color: yellow;
}
}
.zap {
width: 100%;
}
`;
export default function App() {
const [currentProgress, setCurrentProgress] = useState(0);
useEffect(() => {
// I want to update the currentProgress whenever the progress changed becausing of scrolling
setCurrentProgress(0);
}, []);
return (
<ClassToggleStyled>
<div style={{ position: "fixed", top: 0 }}>
Current Progress: {currentProgress}
</div>
<div className="section" />
<div id="trigger" />
<Controller>
<Scene
duration={200}
classToggle="zap"
triggerElement="#trigger"
indicators={true}
>
{(progress, event) => (
<div className="test">
<div style={{ position: "fixed", top: 30 }}>
Progress: {progress}
</div>
Pin Test {event.type} {progress}
</div>
)}
</Scene>
<Scene
classToggle={[".test", "yellow"]}
reverse={false}
indicators={true}
>
<div>Toggle other class</div>
</Scene>
</Controller>
<div className="section" />
</ClassToggleStyled>
);
}
代碼沙盒
https://codesandbox.io/s/nifty-hermann-byrvz?file=/src/App.js
您可以在庫的事件處理程序中設置 state:
{(progress, event) => {
setCurrentProgress(progress);
return (
<div className="test">
<div style={{ position: "fixed", top: 30 }}>
Progress: {progress}
</div>
Pin Test {event.type} {progress}
</div>
)}
}
更新的沙盒
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.