Implementing typewriter effect in React Native

Just run it directly

import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';

export default class TypewriterText extends Component {
  constructor(props) {
    super(props);
    this.state = {
      text: '',
    };
  }

  componentDidMount() {
    this.getUrlsFromApi();
  }

  getUrlsFromApi() {
    // 假设这里从后端接口获取URLs的数据,并模拟一个异步请求
    fetch('https://api.test.com/frontapi/get_app_list')
      .then((response) => response.json())
      .then((data) => {
        // 假设这里获取到了URLs的数据,将 "Data initialization successful" 作为文字内容
        const successText = 'Data initialization successful';
        let currentText = '';
        let currentIndex = 0;

        const typeNextLetter = () => {
          if (currentIndex < successText.length) {
            currentText = successText.slice(0, currentIndex + 1);
            this.setState({ text: currentText });
            currentIndex++;
            setTimeout(typeNextLetter, 100); // 设置每个字母的显示时间间隔,可以根据需要调整
          }
        };

        typeNextLetter();
      })
      .catch((error) => console.log('获取URLs失败:', error));
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.text}>{this.state.text}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
    alignItems: 'center',
    padding: 10,
  },
  text: {
    fontSize: 20,
  },
});

Guess you like

Origin blog.csdn.net/lllomh/article/details/132107201