0

我想在我的应用程序中添加一个可折叠的标题。我为 Header 视图创建了一个单独的组件。

interface Props{
    userData: UserDetails | null
    scrollY: Animated.Value
}
    
const HEADER_EXPANDED_HEIGHT = sizeProportionHeight(320)
const HEADER_COLLAPSED_HEIGHT = sizeProportionHeight(142)

const CollapsableHeader : React.FC<Props> = ({userData, scrollY}) => {
    
   const headerHeight = scrollY.interpolate({
        inputRange: [0, HEADER_EXPANDED_HEIGHT-HEADER_COLLAPSED_HEIGHT],
        outputRange: [HEADER_EXPANDED_HEIGHT, HEADER_COLLAPSED_HEIGHT],
        extrapolate: 'clamp'
    })

    return(
        <Animated.View style={{height: headerHeight, width: SCREEN_WIDTH, position:'absolute', top:0, left: 0}}/>
    )
}

export default CollapsableHeader

在我的主页上,我添加了这样的标题:

interface Props{
    navigation: StackNavigationProp<MainParamList,'HomeScreen'>
    route: RouteProp<MainParamList,'HomeScreen'>
}

interface HeaderState {
    scrollY: Animated.Value   
}

interface HomeScreenState {
    header: HeaderState
}

const HomeScreen : React.FC<Props> = ({ navigation, route }) => {

    const [state, setState] = React.useState<HomeScreenState>({header: {scrollY: new Animated.Value(0)}})

    return (
        <View  style={styles.container}>
            <CollapsableHeader userData={null} 
                               scrollY={state.header.scrollY}/>
            <ScrollView contentContainerStyle={[styles.scrollContainer]}
                        onScroll={Animated.event(
                            [{
                                nativeEvent: {
                                    contentOffset: {
                                        y: state.header.scrollY
                                    }
                                    
                                },
                            }],
                            {
                                useNativeDriver:true
                            }
                            
                        )}
                        scrollEventThrottle={16}>
/// Scrollable content
                </ScrollView>
            </View>
        )
    }

但是,如果我尝试滚动,我会收到一条错误消息

this.props.onScroll is not a function. (In 'this.props.onScroll(e)', 'this.props.onScroll' is an instance of AnimatedEvent)

如果我删除useNativeDriver: true错误消失,而是我收到警告说我失踪了useNativeDriver

如何正确使用此可折叠动画?

4

1 回答 1

1

使用nativeDriver意味着我们可以在动画开始之前将有关动画的所有内容发送到本机,并允许本机代码在 UI 线程上执行动画,而无需在每一帧上都经过桥接。

Native Animated 目前并不支持您可以使用 Animated 执行的所有操作。主要限制是您只能为非布局属性设置动画,例如transformandopacity可以工作,但 Flexbox 和 position 属性不能。

因此,如您所见widthheight不受 支持nativeDriver,您可以禁用它。

useNativeDriver: false

无需完全删除它。

注意:也更改ScrollViewAnimated.ScrollView

于 2020-12-24T09:46:10.587 回答