import React, {useEffect, useState} from 'react';
import {Col} from "native-base";
import {Animated, TouchableOpacity, ViewProps} from "react-native";
interface AnimatedButtonProps extends ViewProps {
text: string;
size: Animated.Value;
onPress: (cb?: () => void) => void;
}
export const AnimatedButton = ({text, size, onPress}: AnimatedButtonProps) => {
const [defaultSize, setDefaultSize] = useState(new Animated.Value(30));
useEffect(() => {
// Update defaultSize from props
setDefaultSize(size);
});
let _onPress = () => {
console.log(defaultSize);
Animated.timing(defaultSize, {
toValue: 50,
duration: 300,
}).start();
console.log(defaultSize);
};
return (
<Col style={{justifyContent: "center", alignItems: "center"}}>
<TouchableOpacity style={{
width: 60,
height: 60,
justifyContent: "center",
alignItems: "center",
}}
onPress={() => onPress(_onPress)}>
<Animated.Text style={{
fontSize: defaultSize,
fontWeight: "bold"
}}>{text}</Animated.Text>
</TouchableOpacity>
</Col>
)
};
我是反应钩子的新手,试图用反应钩子重写我的一个组件。任何人都可以告诉我为什么回调动画不起作用?回调确实触发了,但默认大小根本不会改变。下面是我用"React Class"方式编写的原始组件,它按预期工作。一些帮助将不胜感激:D
class AnimatedButton extends Component<AnimatedButtonProps, AnimatedButtonState> {
state: AnimatedButtonState = initState;
componentDidMount(): void {
const {size} = this.props;
this.setState({
size
})
}
_onPress = () => {
const {size} = this.state;
Animated.sequence([
Animated.timing(size, {
toValue: 50,
duration: 300,
}),
Animated.timing(size, {
toValue: 30,
duration: 300,
})
]).start();
};
render() {
const {text} = this.props;
const {size} = this.state;
return (
<Col style={{justifyContent: "center", alignItems: "center"}}>
<TouchableOpacity style={{
width: 60,
height: 60,
justifyContent: "center",
alignItems: "center",
}}
onPress={() => this.props.onPress(this._onPress)}>
<Animated.Text style={{
fontSize: size,
fontWeight: "bold"
}}>{text}</Animated.Text>
</TouchableOpacity>
</Col>
);
}
}
export default AnimatedButton;
useEffect(() => {
setDefaultSize(size);
}, [defaultSize]);
解决了问题