首页 > 解决方案 > 如何在反应natvie中滚动到滚动视图的开头

问题描述

我是新来的反应本地人。我想做这样的事情。我有水平滚动视图,它有几个选项卡。因此,当用户按下选项卡时,我希望滚动视图滚动到选项卡的开头(到第一个选项卡)。那么我该如何使用 scrollTo() 方法来做到这一点。

    <ScrollView horizontal showsHorizontalScrollIndicator={false} >
              <FilterTab>
                  <Block fluid>
                    <P>
                      TAB 1
                    </P>
                  </Block>
                </FilterTab>
                 <FilterTab>
                  <Block fluid>
                    <P>
                      TAB 2
                    </P>
                  </Block>
                </FilterTab>
                <FilterTab>
                  <Block fluid>
                    <P>
                      TAB 3
                    </P>
                  </Block>
                </FilterTab>
                 <FilterTab>
                  <Block fluid>
                    <P>
                      TAB 4
                    </P>
                  </Block>
                </FilterTab>

      </ScrollView>

标签: react-native

解决方案


您可以通过使用 arefscrollTo()方法来做到这一点:

class YourComponent extends React.Component {

  /*
  With the ref added below, you can call scrollTo() on the scrollview
  via the _myScrollView ref, as follows:
  */
  scrollToTop() {
    this.refs._myScrollView.scrollTo(0);
  }

  render() {

    /* add the _myScrollView ref to your scroll view component */
    return (
      <ScrollView ref='_myScrollView' horizontal 
        showsHorizontalScrollIndicator={false} >
        <FilterTab>
            <Block fluid>
              <P>
                TAB 1
              </P>
            </Block>
          </FilterTab>
            <FilterTab>
            <Block fluid>
              <P>
                TAB 2
              </P>
            </Block>
          </FilterTab>
          <FilterTab>
            <Block fluid>
              <P>
                TAB 3
              </P>
            </Block>
          </FilterTab>
            <FilterTab>
            <Block fluid>
              <P>
                TAB 4
              </P>
            </Block>
          </FilterTab>
        </ScrollView>)
  }

}

推荐阅读