【问题标题】:Dynamically set scrollEnabled to False in RN ScrollView在 RN ScrollView 中将 scrollEnabled 动态设置为 False
【发布时间】:2017-02-11 18:49:57
【问题描述】:

当滚动到某个位置时,如何改变React Native ScrollView的scrollEnabled参数的bool值?

我确实在 ScrollView 中有一个 ScrollView,但由于外部 ScrollView,内部 ScrollView 没有响应。当 scrollEnabled 参数设置为外部 ScrollView 的 False 时,内部 ScrollView 起作用。我的想法是在到达底部时将外部 ScrollView 动态设置为scrollEnabled={false}。我该怎么做。

谢谢,

【问题讨论】:

  • 你到底想要达到什么目的?
  • 使用状态。 'scrollEnabled={this.state.scrollEnabled}' 然后 this.setState({scrollEnabled: false});

标签: react-native react-native-android react-native-listview react-native-scrollview


【解决方案1】:

有两种方法可以做到这一点。第一个,如@binchik 所述,是将 scrollEnabled 设置为状态变量并在必要时更新状态。当然,这会触发重新渲染,这可能是有问题的。第二种方式是直接更新ScrollView组件上的prop,无需重新渲染。你可以这样做:

class DisableScrollWithoutRerender extends React.Component {
  listRef = React.createRef();
  ...
  render() {
    return <ScrollView ref={this.listRef} />;
  }

  disableScroll() {
    const { current: list } = this.listRef;
    list.setNativeProps({ scrollEnabled: false });
  }
}

我个人建议在负担得起的情况下坚持第一个选项,并避免使用第二个选项,除非它正是您需要的。

【讨论】:

  • 您可以找到更多详情here
  • 我知道这个答案晚了 1.5 年,但也许它会对将来偶然发现这个问题的人有所帮助。
  • 我不得不使用this.listRef.setNativeProps({ scrollEnabled: false }); 而不是disableScroll()
  • 当您需要立即禁用滚动时,我会使用此解决方案。例如,当为嵌入在滚动视图中的内容启动拖放操作时。
【解决方案2】:

为您的滚动视图/列表视图提供ref。然后使用以下更改 scrollEnabled 值。

render() {
  return <ScrollView ref="scrollView" />;
}

onSomeEvent() {
  this.refs.scrollView.setScrollEnabled(true); // will enable scroll
}

【讨论】:

    【解决方案3】:

    ScrollView组件有一个prop回调函数onScroll: ({nativeEvent: {contentOffset: {y}}, contentSize: {height}})

    所以你可以在你的状态中有一个scrollEnabled 变量。如果contentOffset.y 等于或大于contentSize.height,则将其设置为true,否则设置为false

    确保您不要拨打不必要的setState 电话。因为即使之前的状态与新的状态完全相同,它也会让组件每次都重新渲染。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-02
      • 1970-01-01
      • 1970-01-01
      • 2018-01-14
      • 1970-01-01
      • 1970-01-01
      • 2013-09-08
      相关资源
      最近更新 更多