我正在尝试制作CustomButton
动画!我使用createAnimatedComponent
和ref
。该按钮显示出来,但是动画不起作用!我试图注释掉CustomButton
中的颜色,以防createAnimatedComponent
中的动画颜色由于它们而没有显示出来,但是什么也没有。
任何帮助将不胜感激。
CustomCreateAnimatedComp.js
const AnimatedButton = Animated.createAnimatedComponent(CustomButton);
export default class CustomCreateAnimatedComp extends Component {
state = {
animation: new Animated.Value(0)
};
// for the ref button
// Here our customButton gets detected by animated,
// and we forward the setNativeProps to native button
setNativeProps = props => {
this.button.setNativeProps(props);
};
startAnimation = () => {
Animated.timing(this.state.animation, {
toValue: 1,
duration: 1500
}).start(() => {
Animated.timing(this.state.animation, {
toValue: 0,
duration: 300
}).start();
});
};
render() {
const animatedColor = this.state.animation.interpolate({
inputRange: [0, 1],
outputRange: [["white", "black"]
});
return (
<View style={styles.container}>
{/* Animated works also on props (like color) not only styles */}
<AnimatedButton
ref={(ref) => (this.button = ref)}
title="Press Me"
onPress={this.startAnimation}
color={animatedColor}
/>
</View>
);
}
}
CutomButton.js
export default class CustomButton extends React.Component {
render() {
return (
<TouchableWithoutFeedback
onPress={this.props.onPress}
style={{ ...this.props.touchableStyle }}
>
<View
onPress={this.props.onPress}
style={{ ...styles.buttonStyle, ...this.props.style }}
>
<Text style={{ ...styles.text, ...this.props.textStyle }}>
{this.props.title}
</Text>
</View>
</TouchableWithoutFeedback>
);
}
}
const styles = StyleSheet.create({
buttonStyle: {
marginVertical: 5,
paddingBottom: 3,
borderRadius: 15,
alignSelf: "center",
backgroundColor: "tomato",
elevation: 7
},
text: {
color: "white",
textAlign: "center"
}
});
谢谢。
答案 0 :(得分:1)
在来自@Jaydeep Galani的提示后,我检查了CustomButton中的样式,并进行了以下更改,现在按钮的标题已设置动画。 谢谢Jaydeep!
<Text style={[ styles.text, {color: this.props.color} ]}>
{this.props.title}
</Text>
这是最后的更改,因此backgroundColor也将起作用。
export default class CustomButton extends React.Component {
render() {
return (
<TouchableWithoutFeedback
onPress={this.props.onPress}
>
<View
onPress={this.props.onPress}
style={[ styles.buttonStyle, {backgroundColor: this.props.backgroundColor}] }
>
<Text style={[ styles.text, {color: this.props.color} ]}>
{this.props.title}
</Text>
</View>
</TouchableWithoutFeedback>
);
}
}
render() {
const animatedColor = this.state.animation.interpolate({
inputRange: [0, 1],
outputRange: ["white", "black"]
});
const animatedBackgroundColor = this.state.animation.interpolate({
inputRange: [0, 1],
outputRange: ["tomato", "lightblue"]
});
return (
<View style={styles.container}>
{/* Animated works also on props (like color) not only styles */}
<AnimatedButton
ref={(ref) => (this.button = ref)}
title="Press Me"
onPress={this.startAnimation}
color={animatedColor}
backgroundColor={animatedBackgroundColor}
// textStyle={animatedColor}
/>
</View>
);
}