【问题标题】:Animate text color change in React-NativeReact-Native 中的动画文本颜色变化
【发布时间】:2017-12-17 10:01:34
【问题描述】:

这个问题已经困扰我一段时间了,我被卡住了。 当用户点击 Touchable 时,我想为我的文本的颜色属性设置动画。

为此,我使用了一个标签。

我缺少什么来完成这项工作?

到目前为止,这是我的组件:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Text, View, TouchableWithoutFeedback, LayoutAnimation, Animated } from 'react-native';

import { CardSection } from './common';
import * as actions from '../actions';

class ListItem extends Component {
  state = {
    colorAnim: new Animated.Text('#000')
  };

  componentWillUpdate() {
    LayoutAnimation.easeInEaseOut();

    Animated.timing(
      this.state.colorAnim,
      {
        toValue: '#47bed1',
        duration: 5000,
      }
    ).start();
  }

  renderDescription () {
    const { library, expanded } = this.props;

    if (expanded) {
      return (
        <CardSection>
          <Text style={styles.textStyle}>
            { library.description }
          </Text>
        </CardSection>
      );
    }
  }

  render() {
    const { titleStyle } = styles;
    const { id, title } = this.props.library;

    return (
      <TouchableWithoutFeedback
        onPress={() => this.props.selectLibrary(id)}
      >
        <View>
          <CardSection>
            <Animated.Text
              style={{
                ...titleStyle,
                color: this.state.colorAnim
              }}
            >
              { title }
            </Animated.Text>
          </CardSection>
          { this.renderDescription() }
        </View>
      </TouchableWithoutFeedback>
    );
  }
}

const styles = {
  titleStyle: {
    fontSize: 18,
    paddingLeft: 15
  },

  textStyle: {
    paddingLeft: 18,
    paddingRight: 5
  }
}

const mapStateToProps = (state, ownProps) => {
  const expanded = state.selectedLibraryId === ownProps.library.id;

  return {
    expanded: expanded
  };
};

export default connect(mapStateToProps, actions)(ListItem);

【问题讨论】:

  • 我认为你需要使用 react-native Interpolate 来完成这项工作

标签: react-native


【解决方案1】:

这里是backgroundColor道具动画的线程,几乎是一样的: Animating backgroundColor in React Native

基本上,您不能直接使用颜色十六进制字符串,而是将您的colorAnim 声明为new Animated.Value(1)()里面的值应该是整数,比如1

并且在渲染开始时,整数值被“插值”为真实颜色,如下所示:

var color = this.state.colorAnim.interpolate({
    inputRange: [0, 1],
    outputRange: ['#858a91', '#ffffff']
});

那么这个color 对象可以用于你的Animated.Textcolor 属性

...
color: color,
...

【讨论】:

  • 这不能用useNativeDriver 原生驱动。有其他选择吗?
  • 这里有两个选项,我看到: 1. 将两个文本组件(显示相同的文本)放在彼此之上(使用绝对布局)。然后,您可以使用NativeDriver 并更改每个文本组件的不透明度。 2.使用react native reanimated v2改变颜色并存档原生性能。
猜你喜欢
  • 1970-01-01
  • 2012-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-13
  • 2016-12-15
  • 2014-01-19
相关资源
最近更新 更多