首页 > 解决方案 > 移动对象时无法插入颜色

问题描述

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

const ANIMATION_DURATION = 250;

class Ball extends Component {
  
  componentWillMount() {
    this.position = new Animated.ValueXY(0,0);
    this.borderC = new Animated.Value(0);
    
    Animated.parallel([
      Animated.timing(this.position, {
        toValue: { x: 200, y: 500 },
        duration: ANIMATION_DURATION
      }),
      Animated.timing(this.borderC, {
        toValue: 1,
        duration: ANIMATION_DURATION,
      })
    ]).start();
  }
  
  
  render() {
    const styl = {
      ball: {
        height: 60,
        width: 60,
        borderRadius: 30,
        borderWidth: 30,
        borderColor: this.borderC.interpolate({
          inputRange: [0, 1],
          outputRange: ['green', 'yellow'],
        })
      }
    }
  
    return (
      <Animated.View style={this.position.getLayout()}>
        <View style={styl.ball}/>
      </Animated.View>
    );
  }
}



export default Ball

我有一个简单的组件,它试图将球从一个点移动到另一个点,同时将颜色从绿色变为黄色。没有错误被抛出并且球确实移动。但是我无法弄清楚哪个部分可能出错了。

我已经实现了让动画同时Animated.parallel运行并interpolateborderColorwithinputRange以及1 and 0outputRange

这是你玩转的世博小吃

标签: react-nativeinterpolationreact-animated

解决方案


View需要border-color转换的第二个组件也应该是一个Animated.View

样本

  render() {
    const style = {
      ball: {
        height: 60,
        width: 60,
        borderRadius: 30,
        borderWidth: 30,
        borderColor: this.borderC.interpolate({
          inputRange: [0, 1],
          outputRange: ['green', 'yellow'],
        })
      }
    }

    return (
      <Animated.View style={this.position.getLayout()}>
        <Animated.View style={styl.ball}/>
      </Animated.View>
    );
  }

推荐阅读