我想制作一个常规的进度条,但它不起作用。
应用程序.tsx:
const [progress, setProgress] = useState(0);
...
useEffect(() => {
setInterval(() => {
setProgress(progress + 1)
}, 1000);
}
});
...
return (
...
<ProgressBar progress={progress} />
...
)
进度条.tsx:
import React, {useEffect} from "react";
import { View, Animated } from "react-native";
type ProgressBarProps = {
progress: number
}
const ProgressBar: React.FC<ProgressBarProps> = (props) => {
const animation = new Animated.Value(props.progress);
useEffect(() => {
Animated.timing(animation, {
toValue: props.progress,
duration: 500
}).start();
console.log(props.progress)
});
return (
<View style={{ flex: 1, borderColor: "red", borderWidth: 2, borderRadius: 4}}>
<Animated.View
style={{
width: animation.interpolate({
inputRange: [0, 1],
outputRange: ["0%", "100%"],
extrapolate: "clamp"
}),
height: '10px',
backgroundColor: 'red'
}}
/>
</View>
);
};
export default ProgressBar;
结果,页面上只显示了一条红色的短线。 https://codesandbox.io/s/github/merrymaker14/react-native-web-example-as-testtask
抓住!useRef 和 useState 都可以用于在组件的整个生命周期中不会重新创建的值。第二个问题是在useEffect中,你需要关闭计时器;)好吧,进度本身是从0到1(我差点忘了;))
https://codesandbox.io/s/react-native-web-example-as-testtask-g667e