背景颜色不透明度插值不起作用

时间:2021-04-28 12:48:51

标签: reactjs react-native react-animated

我想让自定义标题在垂直滚动时从透明变为不透明(当 scrollY 达到 150 时开始并在 250 时完全不透明)。我有以下代码,但不透明度没有更新,我不知道为什么:

import React from 'react';
import { StyleSheet, Animated } from 'react-native';

export default function App() {
    const scrollY = React.useRef(new Animated.Value(0)).current;

    const opacity = scrollY.interpolate({
        inputRange: [0, 150, 250],
        outputRange: [0, 0, 1],
        extrapolate: 'clamp'
    });

    return (
        // Header
        <Animated.View
            style={{
                ...styles.header,
                backgroundColor: `rgba(255, 255, 255, ${opacity})`
            }}
        >
                /* some content */
        </Animated.View>

        // Vertical list
        <Animated.FlatList
            onScroll={Animated.event(
                [{ nativeEvent: { contentOffset: { y: scrollY } } }],
                { useNativeDriver: false }
            )}
            data={DATA}
            keyExtractor={(item, index) => index.toString()}
            renderItem={renderItem}
            ListHeaderComponent={ListHeader}
        />
    );
}

1 个答案:

答案 0 :(得分:1)

您可以直接插入 backgroundColor

const backgroundColor = animValue.interpolate({
    inputRange: [0, 150, 250],
    outputRange: ['#00000000', '#00000000', '#FFF'], // You can play around it
    extrapolate: 'clamp'
})

...

<Animated.View
    style={{
        ...styles.header,
        backgroundColor
    >