重新渲染组件时如何防止自动滚动到顶部?

时间:2020-04-19 08:45:47

标签: list react-native scrollview native-base

我在与nativebase进行本机交互时面临一个问题。

<Content> 
   <List> 
     <ListItem> 
      <Left style={{ flex: 0 }}>
         <Icon name="user" type="SimpleLineIcons"></Icon>
      </Left>
      <Body>
         <Text> Profile </Text>
      </Body>
      <Right>
         <Switch value={this.state.profile} />
      </Right>
     </ListItem>
     ....
   </List> 
</Content> 

当我更新状态(渲染组件)列表时,列表会自动滚动到顶部/第一位置:

this.setState({profile: true });

如何防止自动滚动以获得更好的用户体验?

2 个答案:

答案 0 :(得分:1)

请在<Content>组件中尝试使用此道具:

<Content enableResetScrollToCoords={false} />

您也可以尝试此解决方案:

handleScroll(event) {
    this.setState({ scrollY: event.nativeEvent.contentOffset.y });
}

render() {
    if (this.contentRef) {
      if (this.contentRef._scrollview) {
        this.contentRef._scrollview.resetScrollToCoords({ x: 0, y: this.state.scrollY });
      }
    }

    return (
        <Content
          ref={(c) => this.contentRef = c}
          onScroll={event => this.handleScroll(event)}
        >
    );
}

答案 1 :(得分:0)

我创建了功能列表组件,并在抽屉中进行渲染。在抽屉中有文字和开关组件。

我的列表组件位于renderer方法内部,因此每当我切换开关render方法时,fire和list autocamatilly都会上升。

现在,我将列表组件置于render方法之外。这解决了我的问题。

感谢大家的快速反应和建议。

示例:

render(){
const drawerContent = ()=>(
<Content> 
 <List> 
  <Switch value={this.state.flag) />
 </List>
</Content> 
)
return(
<Drawer content={drawerContent}>
 <Container> 
  ....
 </Container> 
</Drawer>
)
}

收件人

drawerContent = ()=>(
<Content> 
 <List> 
   <Switch value={this.state.flag) />
 </List>
</Content> 
)
render(){
return(
<Drawer content={this.drawerContent}>
 <Container> 
  ....
 </Container> 
</Drawer>
)
}