代码之家  ›  专栏  ›  技术社区  ›  flix

React Native-如何舍入动画组件的值?

  •  0
  • flix  · 技术社区  · 6 年前

    我想创建文本动画使用 Animated API 但是动画的值是十进制的,我想四舍五入那个值,有可能吗?

    我试过使用 Math.round() 但结果是 NaN ,

    代码如下:

    const AnimatedText = Animated.createAnimatedComponent(CustomText);
    
    
    export default class App extends Component {
      constructor(props) {
        super(props);
        this.visited = new Animated.Value(0)
      }
    
      componentWillMount(){
        Animated.timing(this.visited,{
          toValue: 1,
          duration:1000,
        }).start();
      }
    
      render(){
        const visiting = this.visited.interpolate({
          inputRange: [0, 1],
          outputRange: [0, 20],
        });
        return(
          <AnimatedText style={{fontSize:40, color:'white', fontWeight:'900'}}>{visiting}</AnimatedText>
        )
      }
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   James_F    6 年前

    这是因为 new Animated.Value 创建自定义的本机对象。如果要获取该值,可以停止动画并获取当前值:

    this.state.visited.stopAnimation(value => console.log(Math.round(value.value)))
    

    componentWillMount(){
        this.state.visited.addListener(value => console.log(Math.round(value.value)))
        Animated.timing(this.visited,{
          toValue: 1,
          duration:1000,
        }).start();
    } 
    

    https://facebook.github.io/react-native/docs/animations.html#responding-to-the-current-animation-value

    推荐文章