1
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>
    )
};

我是反应钩子的新手,试图用反应钩子重写我的一个组件。谁能告诉我为什么回调动画不起作用?回调确实触发了,但 defaultSize 根本没有改变。下面是我以“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;
4

1 回答 1

0
    useEffect(() => {
        setDefaultSize(size);
    }, [defaultSize]);

解决了问题

于 2020-01-14T15:14:28.270 回答