如何在react-native中更改动画中的文本?

时间:2017-08-28 09:16:44

标签: react-native

我使用Animated.Text更改动画文本,但它无法正常工作

我还要求在动画中淡出旧文字和&淡入新文本。

import React, { Component, PropTypes } from 'react';
import {
    StyleSheet,
    View,
    Text,
    Image,
    Dimensions,
    Animated
} from 'react-native';
import styles from './styles';

const win = Dimensions.get('window');

export default class Logo extends Component {
    constructor(props) {
        super(props);
        this.tempText = new Animated.Value("Hello");
    }

    componentWillMount () {
        Animated.timing(this.tempText, {
            duration: 5000,
            toValue: "New Text",
        }).start();
    };

    render() {
        return (
            <View style={{flex:1}}>
                <Animated.Text style={{color: "#9b9b9b"}}>
                    {this.tempText}
                </Animated.Text>
            </View>
        );
    }
}

实际输出获取 - 在5秒后更改文本,但它不起作用。请帮助我。

2 个答案:

答案 0 :(得分:3)

您可以在不使用Animated的情况下完成您尝试实现的目标,实际上Animated并非针对此特定用途。

可以使用简单变量替换文本,并且setTimeout可以触发文本更改。

动画用于更改数值,而不是文本值。可以这样想 - 如果改变应该在5秒的时间间隔内发生,那么中间值会是什么?

请改为:

export default class Logo extends Component {
    constructor(props) {
        super(props);
        this.state = {text: "Hello"};
    }

    componentDidMount () {
        setTimeout(() => this.setState({text: "New Text"}), 5000);
    };

    render() {
        return (
            <View style={{flex:1}}>
                <Animated.Text style={{color: "#9b9b9b"}}>
                    {this.state.text}
                </Animated.Text>
            </View>
        );
    }
}

答案 1 :(得分:1)

我的平滑不透明动画示例。 对不起,没有fadeIn,fadeOut。

const inputRange = [0, 1, 2, 3];
const AnimatedText = Animated.createAnimatedComponent(Text);
    const animationProps = {
      duration: 500,
      easing: Easing.out(Easing.linear),
      isInteraction: false,
      useNativeDriver: true,
    };

class Onboarding extends PureComponent {
  activeDot = 0;
  animationDot = new Animated.Value(0);

  toggleOnButton = () => {
      Animated.timing(this.animationDot, {
        toValue: this.activeDot + 1,
        ...animationProps,
      }).start((endState) => {
        if (endState.finished) {
          this.activeDot = this.activeDot + 1;
        }
      });
  }

  renderButton = () => {
    const opacityNext = this.animationDot.interpolate({
      inputRange,
      outputRange: [1, 1, 1, 0]
    });
    const opacityGetStarted = this.animationDot.interpolate({
      inputRange,
      outputRange: [0, 0, 0, 1]
    });
    return (
      <TouchableOpacity style={styles.button} onPress={this.toggleOnButton}>
        <AnimatedText style={[styles.buttonText, { opacity: opacityNext }]}>
          Next
        </AnimatedText>
        <AnimatedText style={[styles.buttonText, {
            top: normalize(isIOS ? 12 : 8), position: 'absolute', opacity: opacityGetStarted
          }]}
        >
          Get started
        </AnimatedText>
      </TouchableOpacity>
    );
  }
}