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

时间:2019-01-09 03:18:06

标签: javascript reactjs react-native

我想使用Animated API创建文本动画,但是animation的值具有小数,我想舍入该值,可以吗?

我尝试使用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 个答案:

答案 0 :(得分:1)

这是因为new Animated.Value创建了一个自定义的react native对象。如果要获取值,则可以停止动画并获取当前值:

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