命令性地从 React Native 动画请求插值

Ian*_*rty 6 animation interpolation colors react-native

我正在尝试从 react-native 动画中检索当前颜色。它被映射interpolate到一组颜色字符串。

class IconTransition extends React.Component<Props, State> {
  protected _param: number = 0;

  constructor(props: Props) {
    super(props);

    this.state = {
      param: new Animated.Value(0)
    };

    this.state.param.addListener(param => {
      this._param = param.value;
    });
  }

  componentDidMount() {
    Animated.spring(this.state.param, {
      mass: 1,
      stiffness: 10,
      damping: 10,
      toValue: 1
    });
  }

  componentWillReceiveProps() {
    // I want to do something like this. Would be awesome
    // if I could avoid the listener in the constructor.
    //
    // const currentColor = Animated.interpolate.get({
    //   currentInput: this._param,
    //   outputRange: ["#FFFFFF", "#000000"]
    // });
  }

  render() {
    return (
      <AnimatedIcon
        {...this.props}
        color={this.state.param.interpolate({
          inputRange: [0, 1],
          outputRange: ["#FFFFFF", "#000000"]
        })}
      />
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

如果动画未完成,我想检索插入的颜色。我知道我可能会使用像chroma-js这样的外部库(特别是chroma.mix函数)来实现这一点 - 但是有不同的方法可以通过两种不同的颜色进行插值,我宁愿不依赖外部库,如果我可以避免它。

所以......更大的问题仍然存在,我如何强制请求来自interpolationAPI的输出值?我们可以不listen使用内插值Animated.Value()吗,就像我们做的那样?

jee*_*eev 5

我尝试做同样的事情有一段时间了,你需要记住一些事情:

如果你把所有这些放在一起,你可以得到如下内容,这在我的情况下有效:

import React from 'react';
import {View, processColor} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';

class BackgroundColorLinearGradientText extends React.Component {

    /**
     * Class constructor.
     */
    constructor(props, context) {
        super(props, context);
        this.backgroundColor = new Animated.Value(0);
        this.backgroundColor.addListener(i => {
            let interpolated = this.backgroundColor.interpolate({
                inputRange: [0, 1],
                outputRange: ['#FF0000', '#00FF00'],
            }).__getValue();
            if (this.background) {
                this.background.setNativeProps({colors: [processColor(interpolated), processColor(this.background.props.colors[1])]})
            }
        });
    }

    componentDidMount() {
        Animated.timing(this.backgroundColor, {
            toValue: 1,
            duration: 3000,
        }).start();
    }

    render() {
        return (
            <LinearGradient ref={i => this.background = i} colors={['red', 'blue']} style={{flex: 1}}>
                <View style={{
                    flex: 1,
                    justifyContent: 'center',
                    alignItems: 'center',
                }}>
                    Content
                </View>
            </LinearGradient>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

这将创建一个具有红色到蓝色渐变背景的屏幕,在三秒钟内过渡到绿色到蓝色。