react-native - React Native 使用 Animated 隐藏 Header(在 TransformY 后留下空白)

标签 react-native react-native-reanimated

我已经使用 Animated 在 React Native 中实现了滚动时隐藏标题。 这是代码:

const y = new Animated.Value(0);
const AnimatedWebView = Animated.createAnimatedComponent(WebView);
const HEADER_HEIGHT = 60;
const {diffClamp} = Animated;

function WebPage({route}) {
  const diffClampY = diffClamp(y, 0, HEADER_HEIGHT);
  const translateY = diffClampY.interpolate({
    inputRange: [0, HEADER_HEIGHT],
    outputRange: [0, -HEADER_HEIGHT],
  });
  return (
    <SafeAreaView style={{flex: 1}}>
      <Animated.View
        style={{
          height: HEADER_HEIGHT,
          width: '100%',
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          zIndex: 2,
          backgroundColor: 'lightblue',
          transform: [{translateY: translateY}],
        }}
      />
      <AnimatedWebView
        source={{
          uri: 'https://www.stackoverflow.com',
        }}
        originWhitelist={['*']}
        containerStyle={{paddingTop: 60}}
        bounces={false}
        onScroll={Animated.event([{nativeEvent: {contentOffset: {y: y}}}])}
      />
    </SafeAreaView>
  );
}

由于 Header 绝对定位在顶部,因此我给出了 paddingTop(与 header 的高度相同)以避免 header 最初与 WebView 的内容重叠。现在正因为如此,当我滚动时,随着标题消失,它会留下空白,如图所示:

Before hiding the Header

After hiding the Header

上面是隐藏标题之前和之后的图像。原来标题所在的位置留有空白。我应该如何动态更改填充,以便当标题消失时,不留空白?我尝试过没有绝对定位标题,也没有给 Webview 提供 paddingTop,但仍然是空白。

任何帮助表示赞赏!谢谢

最佳答案

当您使用translateY时,这意味着您正在将标题移离其当前位置,而不是其所在的位置。您看到的空白区域是标题的 anchor (打开调试器,您将看到标题组件仍处于旧位置)。为了移动您的 webview,只需将 webview 的 translateY 与您的标题绑定(bind),您将获得完美的动画。

<AnimatedWebView
    source={{
      uri: 'https://www.stackoverflow.com',
    }}
    originWhitelist={['*']}
    containerStyle={{paddingTop: 60}}
    bounces={false}
    onScroll={Animated.event([{nativeEvent: {contentOffset: {y: y}}}])}
    style={{
        transform: [{translateY: translateY}]
    }}
/>

编辑 1

我正在考虑 3 个解决方案:

  1. 您将更改 WebView 的高度及其位置。看看这个:Increase width height of view using animation .
  2. 使您的 WebView 的高度大于其默认高度。所以当你翻译webview时,多余的空间会覆盖你的空白。在这种情况下,您必须使用 React Native Dimension 计算 webview 的高度
  3. 有一个变换的属性,称为scale。你可以用它来拉伸(stretch)你的webview,但我不知道它是否会拉伸(stretch)你的webview的内容。

关于react-native - React Native 使用 Animated 隐藏 Header(在 TransformY 后留下空白),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59816301/

相关文章:

React-Native - reanimated-bottom-sheet - 无法向上/向下拖动底部工作表

android - React-Native:显示加载屏幕直到加载 webview

javascript - 将 TinyMCE WYSIWYG HTML 编辑器集成到 React Native 应用程序

reactjs - React Native 复活不适用于插值

react-native - 当我尝试使用 PanGestureHandler 移动盒子时 onGestureEvent 未被调用

reactjs - react native 动画动画工作一次

javascript - Reanimated 2 不能使用具有直接值的 withSequence

react-native - 未强制执行 ReactiveSearch 默认查询

android - Android 上 React Native 应用程序周围的粗黑边/边框

javascript - 异步存储 React Native 获取项目