Javascript React Native-如何舍入动画组件的值?
我想使用Javascript React Native-如何舍入动画组件的值?,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我想使用动画API创建文本动画,但动画的值有小数,我想舍入该值,可以吗 我尝试过使用Math.round(),但输出是NaN 代码如下: const AnimatedText = Animated.createAnimatedComponent(CustomText); export default class App extends Component { constructor(props) { super(props); this.visited = new Ani
动画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>
)
}
}
const AnimatedText=Animated.createAnimatedComponent(自定义文本);
导出默认类应用程序扩展组件{
建造师(道具){
超级(道具);
this.visted=新的动画.Value(0)
}
组件willmount(){
动画。计时(本次访问{
toValue:1,
持续时间:1000,
}).start();
}
render(){
const visting=this.visted.interpolate({
输入范围:[0,1],
输出范围:[0,20],
});
返回(
{访问}
)
}
}
这是因为新建动画.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();
}
如果值是一个数字,则可能首先检查该值,如果是,则可以将其传递给
Math.round
,即typeof value=='number'?Math.round(value):0
我上次使用了typeof
,结果是object
,那么返回的动画值不是有效的js数字。您是否可以尝试将动画值记录到控制台日志中,以检查对象是否具有任何可以舍入的数值属性