首页 > 解决方案 > Animated.View 仅适用于展开,不适用于折叠

问题描述

我在使用<Animated.View />. 以下仅适用于toValue设置为40。它很好地扩展并且动画有效。在折叠时(将 设置toValue0),它只是混合在一起 - 好像可见性设置为none。这是为什么?

const Foo = () => {
    const [bounceValue, setBounceValue] = useState(new Animated.Value(0));
    const [collapsed, setCollapsed] = useState(true);
    const height = { height: bounceValue };
    
    const _slideInOut = () => {
        let toValue;
        if (collapsed) {
            toValue = 40;
            setCollapsed(false);
        } else {
            toValue = 0;
            setCollapsed(true);
        }
        Animated.timing(bounceValue, {
            toValue: toValue,
            duration: 400,
            useNativeDriver: false
        }).start();
    }

    return <TouchableOpacity
        activeOpacity={1}
        style={[
            styles.container,
            ...
        ]}
        onPress={() => _slideInOut()}>
        <Animated.View
            style={[
                height,
                styles.menu,
            ]}>
            ...
        </Animated.View>
    </TouchableOpacity>
}

const styles = StyleSheet.create({
    container: {
        width: '100%',
        top: 0,
        height: 10,
        position: 'absolute',
    },
    menu: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        backgroundColor: 'white',
        position: 'absolute',
        top: 10,
        width: '100%'
    }
})

标签: javascriptreact-nativeanimationmobilereact-animated

解决方案


您想为此使用 ref:

const bounceValue = useRef(new Animated.Value(0)).current;

推荐阅读