gpt4 book ai didi

reactjs - 完成后如何更新进度并执行代码react-native

转载 作者:行者123 更新时间:2023-12-04 10:56:32 24 4
gpt4 key购买 nike

我对 native 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/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com