React-native 组件不工作,它循环并在 UI 上显示增加的值

React-native component not working which loops through and shows increasing value on UI

我正在尝试构建一个组件,我正在尝试更新 for 循环中的视图以在 UI、

上呈现值

我要实现的伪代码:

1.for 1..100

  1. 增量:var + 1

  2. 更新视图以更新 var 值

注意:我想要递增值的视觉效果。

下面的代码写到现在,没有更多的线索。请指导我。

export default class App extends React.Component {

  state = {
    amount: 45,
  }

  increaseAmount = () => {
    for (var i = 0; i < 10; i++) {
      let amt = this.state.amount + 1;
      setTimeout(() => {
        this.setState({
          timePassed: true,
          amount: amt
        })
      }, 100);
    }
  };

  render() {
    return ( <
      View style = {
        styles.container
      } >
      <
      Text > Hello World {
        this.state.amount
      } < /Text> <
      Button title = "Click me"
      onPress = {
        () => this.increaseAmount()
      } > < /Button> <
      /View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
flex: 1,
justifyContent: 'center',
alignItems:'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
  },
});

提前致谢。

您可以通过 Animated 实现:

import { Animated, Text, View } from "react-native";

export default class Counter extends React.Component {
    constructor(props) {
        super(props);

        const amount = 45;

        this.animatedAmount = new Animated.Value(amount);
        this.animatedAmount.addListener(this.onAmountChange);

        this.state = { amount };
    }

    increaseAmount = (amount) => {
        Animated.timing(this.animatedAmount, {
            duration: 1000,
            toValue: this.state.amount + amount,
            useNativeDriver: true
        }).start();
    };

    onAmountChange = (e) => {
        this.setState({
            amount: Math.floor(e.value)
        });
    };

    render() {
        return (
            <View style={styles.container}>
                <Text> Hello World {this.state.amount} </Text>{" "}
                <Button title="Click me" onPress={() => this.increaseAmount(45)}>
                    {""}
                </Button>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        paddingTop: Constants.statusBarHeight,
        backgroundColor: "#ecf0f1",
        padding: 8
    }
});


  increaseAmount = () => {

    let myInterval;

    myInterval = setInterval(() => {
      if (this.state.amount === 99)
        clearInterval(myInterval);
      this.setState({
        timePassed: true,
        amount: this.state.amount + 1
      })
    }, 100);
  };