我正在遵循以下 React Native 教程: https://facebook.github.io/react-native/docs/animated.html
但是,我在运行代码时收到以下警告: 失败的道具类型:提供给RCTView
的object
类型的道具opacity
无效
当调用 fade(( 时,组件在没有动画的情况下消失。
下面是一个示例代码:
import React, { Component } from 'react';
import {
AppRegistry,
Text,
View,
Animated,
StyleSheet
} from 'react-native';
import Icon from 'react-native-vector-icon/FontAwesome'
export default class Sample extends Component {
state = {
fadeAnim: new Animated.Value(0),
}
fade() {
Animated.timing( // Animate over time
this.state.fadeAnim, // The animated value to drive
{
toValue: 1, // Animate to opacity: 1 (opaque)
duration: 10000, // Make it take a while
}
).start(); // Starts the animation
}
render() {
let { fadeAnim } = this.state;
return (
<View style={styles.container}>
<TouchableHighlight onPress={() => {this.fade()}}>
<Icon name="circle" size={30} color="#fff" style={{opacity: fadeAnim}}
>
</TouchableHighlight>
</View>
);
}
......
}
您应该将视图更改为 Animated.View。然后,您可以选择添加插值fadeAnim
以实现更精细的控制。
这样的事情应该有效...
render() {
const { fadeAnim } = this.state;
// optionally tweak the input / output range to suit your needs
const opacity = fadeAnim.interpolate({
inputRange: [0, 1],
outputRange: [0, 1]
});
return (
<Animated.View style={[styles.container, opacity]}>
<TouchableHighlight onPress={() => {this.fade()}}>
<Icon name="circle" size={30} color="#fff"
>
</TouchableHighlight>
</Animated.View>
);
}
您可能不希望淡化容器视图,在这种情况下,将 Animated.View 移到可触摸对象中。
尝试使用背景颜色的 alpha 值来改变不透明度。
<Icon name="circle" size={30} color="#fff" style={{opacity: fadeAnim}} />
自
...
let faceRgb = 'rgba(0,0,0,' + faceAnim + ' )';
return (
...
<Icon name="circle" size={30} color="#fff" style={{backgroundColor: faceRgb}} />
...
)
我有一个类似的问题,但我的问题是因为我试图使用样式表对象,如下所示
export const Skeleton = () => {
const opacity = useRef(new Animated.Value(0));
const styles = StyleSheet.create({
skeleton: {
flex: 1,
backgroundColor: `rgb(210, 210, 210)`,
position: 'relative',
borderRadius: Number(borderRadius),
width: width,
height: height,
opacity: opacity.current
}
})
useEffect(() => {
Animated.loop(
Animated.sequence([
Animated.timing(opacityVal, { toValue: 0.3, duration: 500, useNativeDriver: true }),
Animated.timing(opacityVal, { toValue: 1, duration: 400, useNativeDriver: true })
])
).start()
}, [opacity])
return (
<Animated.View style={ styles.skeleton } />
)
}
所以我不得不从样式表对象中删除不透明度并将其直接添加到 JSX 中,如下所示
return (
<Animated.View style={[styles.skeleton, { opacity: opacity.current }]} />
)
为了提高可读性,我将其他 css 保留在对象中,并在样式道具中使用了一个数组,因此除了其他 css 之外,我还可以在添加不透明度。
您的代码中存在问题:
图标标签不能在动画中使用,所以要做出原生投诉。
相反,您应该用以下任一方式包装图标:TouchableHighlight,TouchableNativeFeedback,TouchableOpacity,TouchableWithoutFeedback,无论哪种有效。
https://facebook.github.io/react-native/docs/touchablewithoutfeedback.html
并将属性绑定到可触摸*而不是图标。