我对 react 原生还很陌生。我正在尝试创建一个带有进度指示器的按钮,并希望在进度完成时执行一些代码。不知何故,我使用以下代码实现了所需的行为,
react 组件
class ProgressButton extends Component {
constructor() {
super();
this.state = {
progress: 100,
};
this.progressTimer = null;
}
componentDidMount() {
this.progressTimer = setInterval(() => {
if(this.state.progress === 0) {
clearInterval(this.progressTimer);
// Run code on completion
}
this.setState({progress: this.state.progress - 1})
}, 100)
}
render() {
return (
<button style={{backgroundPosition: this.state.progress + '%'}}>
Hello
</button>
);
}
}
CSS
button {
font-size: 16px;
width: 70px;
height: 30px;
border-radius: 4px;
border: none;
background-size: 200% 100%;
background-image: linear-gradient(to right, black 50%, grey 50%);
color: white;
background-position: 100% 0;
}
但我对这个解决方案不满意,因为,
- 进度动画不流畅。
- 我认为使用
setInterval()
不是一个好主意。
我考虑过使用 CSS @keyframes
动画和 setTimeout()
执行相同的操作,以在完成时执行代码。但我也不确定,因为它可能不同步。
有更好的方法吗?
最佳答案
friend 我用动画缩短了你的路
import { Animated} from 'react-native';
//in constructor
this.state = {
progress: new Animated.Value(0);
};
//in componentDidMount
Animated.timing(this.state.progress, {
toValue: 100,//That you are interested
duration: 500
}).start()
//in render
const animator = this.state.progress.interpolate({
inputRange: [0, 100],
outputRange: ['1%', '100%'],
});
//use animator in style
<Animated.View style={{height:animator}}/>
为你
import React, {Component} from 'react';
import {View, Text, Animated, Easing, TouchableHighlight} from 'react-native';
class App extends Component {
constructor() {
super();
this.ani = new Animated.Value(0);
}
componentDidMount(): void {
Animated.timing(this.ani, {
toValue: 2,
duration: 3000,
easing: Easing.linear,
}).start(() => {
// Do something after animation (optional).
});
}
render() {
const animator = this.ani.interpolate({
inputRange: [0, 1],
outputRange: ['5%', '100%'],
});
return (
<Animated.View
style={{
flex: 1,
justifyContent: 'center',
}}>
<Animated.View
style={{
height: 60,
backgroundColor: 'blue',
width: animator,
}}>
<TouchableHighlight>
<Text>press me</Text>
</TouchableHighlight>
</Animated.View>
</Animated.View>
);
}
}
export default App;
关于reactjs - 如何更新进度并在完成后执行代码react-native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59143613/