Проблема с реагирующими хуками с анимацией обратного вызова - PullRequest
0 голосов
/ 14 января 2020
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», который работает, как ожидалось. Некоторая помощь будет по достоинству оценена: 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;

1 Ответ

0 голосов
/ 14 января 2020
    useEffect(() => {
        setDefaultSize(size);
    }, [defaultSize]);

Решил проблему

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...