React-native компонент не работает, который проходит через все и показывает возрастающее значение в пользовательском интерфейсе - PullRequest
0 голосов
/ 26 октября 2019

Я пытаюсь создать компонент, в котором я пытаюсь обновить представление для цикла for, чтобы отобразить значение в пользовательском интерфейсе,

Псевдокод того, что я пытаюсь реализовать:

1.for 1..100

Инкремент: var + 1

Обновите представление для обновления значения 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,
  },
});

Заранее спасибо.

Ответы [ 2 ]

1 голос
/ 26 октября 2019
  increaseAmount = () => {

    let myInterval;

    myInterval = setInterval(() => {
      if (this.state.amount === 99)
        clearInterval(myInterval);
      this.setState({
        timePassed: true,
        amount: this.state.amount + 1
      })
    }, 100);
  };
1 голос
/ 26 октября 2019

Вы можете достичь этого с помощью 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
    }
});


...