React-Native ScrollView在setState上丢失了位置

时间:2017-10-02 05:55:41

标签: ios react-native scrollview react-native-ios setstate

我需要在ScrollView中更改行的状态(在ListView中相同),但使用组件的setState会使滚动重置其位置到顶部。

          <ScrollView
        {...this.panResponder.panHandlers}
        bounces={false}
        onScroll={() => {
          this.scrollIsScrolling = true;
        }}
        onTouchEnd={() => {
          this.scrollIsScrolling = false;
        }}
        onMomentumScrollEnd={() => {
          this.scrollIsScrolling = false;
        }}
        scrollEnabled={this.state.scrollEnabled}
        removeClippedSubviews={false}
        enableEmptySections
        style={styles.listView}
      >
        {this.props.settings.map((setting, i) => {
          return (
            <IntegrationSlideupCell
              key={i}
              title={setting.title}
              selected={this.state.selectedSetting === i}
              selectedGradient={this.props.integration.selectedGradient}
              onPress={() => {
                this.setState({ selectedSetting: i });
              }}
            />
          );
        })}
      </ScrollView>

UPD:删除自定义panHandlers,onScroll,onTouchEnd,onMomentumScrollEnd处理程序和其他道具没有任何区别。唯一导致它setState的东西。

1 个答案:

答案 0 :(得分:-1)

使用偏移量方法,如果为“ IntegrationSlideupCell”指定了固定高度,则可以偏移该宽度并将偏移量存储到状态

this.state = {
    contentOffset: {y: 0},
}

function handlePress() {
   offset = HEIGHT_OF_CONTAINER;
   newOffset = this.state.contentOffset.y + offset;    
   this.setState({contentOffset: {y: newOffset}, selectedSetting: i });
} 

          <ScrollView
    {...this.panResponder.panHandlers}
    bounces={false}
    contentOffset={this.state.contentOffset}
    onScroll={() => {
      this.scrollIsScrolling = true;
    }}
    onTouchEnd={() => {
      this.scrollIsScrolling = false;
    }}
    onMomentumScrollEnd={() => {
      this.scrollIsScrolling = false;
    }}
    scrollEnabled={this.state.scrollEnabled}
    removeClippedSubviews={false}
    enableEmptySections
    style={styles.listView}
  >
    {this.props.settings.map((setting, i) => {
      return (
        <IntegrationSlideupCell
          key={i}
          title={setting.title}
          selected={this.state.selectedSetting === i}
          selectedGradient={this.props.integration.selectedGradient}
          onPress={handlePress.bind(this)}
        />
      );
    })}
  </ScrollView>