React Native 系列【五】View 滑动时禁止 WebView 滚动

本贴最后更新于 2456 天前,其中的信息可能已经天翻地覆

SymApp

ToC

知识点

想快速解决的请直接看最后一节的解决方案

问题描述

在使用 React Navigation 时, 虽然各个 View 切换的性能和效果都非常不错,也可以用 transitionConfig 很方便的进行自定义切换效果。但是如果你从一个原生的 React Native 页面点击后跳转到一个使用 WebView 的页面时,问题就来了。

iOS 下,当我在 WebView 中用从最左滑到右的手势想回到前一个 View 时,我的手如果上下移动了。这个时候 WebView 也会跟着上下移动。

解决过程

  1. 查看如何让 WebView 不滚动 -> scrollEnabled
  2. 找 navigation 切换时的事件回掉,然而在返回上一页的切换过开始时,onTransitionStart 并不会被触发。还好在整个过程中详细的了解了 navigation。
onTransitionStart: () => {
    this.props.navigation.state.isScroll = 1;
    console.log(Article.props.isScroll = false);
  },
  onTransitionEnd: () => {
    console.log(arguments, 2);
  },
  transitionConfig: () => ({
    screenInterpolator: (sceneProps) => {
      const { layout, position, scene } = sceneProps;
      const { index } = scene;

      const height = layout.initHeight;
      const translateY = position.interpolate({
        inputRange: [index - 1, index, index + 1],
        outputRange: [height, 0, 0]
      });

      const opacity = position.interpolate({
        inputRange: [index - 1, index - 0.99, index],
        outputRange: [0, 1, 1]
      });

      return { opacity, transform: [{ translateY }] };
    }
  })

3 . 本想放弃的,要么不要切换效果,要么换个切换效果,要么就不用 WebView,要么就忽略在 iPhone 上回退时手闲的去上下滑动的人(这样的人应该比较少吧)
4 . 最后在放弃的哪天,和同事吃晚饭,聊了下。我的方向错了,这个属于 gesture,并不是 navigation

解决方案

其实蛮简单的,但是一开始的时候思路错了。一直往 navigator 组件上找,看各种 API,找各种事件劫持回掉。。。其实只要用 gesture 就可以简单搞定了

class Article extends Component {

  static propTypes = {
    navigation: PropTypes.object.isRequired
  };

  constructor(props) {
    super(props);
  this.state = {
      scrollEnabled: true
  };
  }

  componentWillMount() {
    this._gestureHandlers = {
      onStartShouldSetResponder: () => true,
  onResponderGrant: () => {
        this.setState({ scrollEnabled: true });
  },
  onResponderTerminate: () => {
        this.setState({ scrollEnabled: false });
  }
    };
  }

  render() {
    const { params } = this.props.navigation.state;
  return (
       style={utils.statusBar} {...this._gestureHandlers}>
   scrollEnabled={this.state.scrollEnabled}
          source={{ uri: `https://hacpai.com/article/${params.oId}` }}
        />
   );
  }
}
  • Webview
    7 引用 • 33 回帖 • 1 关注
  • gesture
    1 引用 • 29 回帖
  • React

    React 是 Facebook 开源的一个用于构建 UI 的 JavaScript 库。

    192 引用 • 291 回帖 • 443 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...
Vanessa
我们终此一生,就是要摆脱他人的期待,找到真正的自己。 昆明