【问题标题】:React-Native style a sticky header when it sticksReact-Native 在粘贴时设置粘性标题
【发布时间】:2017-07-02 19:32:08
【问题描述】:

我有一个简短的问题:如何在滚动视图中将不同的样式应用于粘性标题?
我想在它粘住时添加一些阴影/高度。

谢谢你:)

环境

  • 反应原生:0.45.0

【问题讨论】:

  • 收听 onscroll 并在 header 粘贴时使用 state 更改组件的样式。
  • @SagarKhatri 感谢您的评论!我怎么知道标题何时粘住?是否有特殊事件或方法可以获取组件在滚动视图中的偏移量?
  • @DanielLang你最后找到方法了吗?

标签: styling react-native-scrollview react-native


【解决方案1】:

目前React NativeScrollView 组件有一个名为stickyHeaderIndices 的属性,即使在您的0.45 版本中也是如此。您可以使用它来传递应该具有粘性的标题子索引。之后,您可以使用onScroll 事件获取当前滚动位置,并在达到您的标题大小时添加带有阴影的自定义样式。请参阅此处的示例:

https://snack.expo.io/@fabiodamasceno/scroll-sticky-styled

或者如果您愿意:

import * as React from 'react';
import { Text, View, ScrollView } from 'react-native';

const HEADER_HEIGHT = 20;
const headerStyle = {
  backgroundColor: '#e5e5e5',
  height: HEADER_HEIGHT
}
const myShadowStyle = {
  elevation: 3,
  shadowOpacity: 0.2,
  shadowRadius: 6,
  shadowOffset: {
    height: 3,
    width: 0,
  },
};

export default class App extends React.Component {
  state = {
     headerStyle : {
     ...headerStyle
    }
  }
  render() {
    return (
     <View style={{marginTop: HEADER_HEIGHT, height: 150}}>
      <ScrollView 
        stickyHeaderIndices={[0]} 
          onScroll={event => {
            const y = event.nativeEvent.contentOffset.y;
            if(y >= HEADER_HEIGHT)
              this.setState({
                headerStyle:{
                    ...headerStyle,
                    ...myShadowStyle
                }
              })
            else
              this.setState({
                  headerStyle:{
                      ...headerStyle,
                  }
                })
          }}
      >
        <View style={this.state.headerStyle}>
          <Text>My Header Title</Text>
        </View>
        <Text>Item 1</Text>
        <Text>Item 2</Text>
        <Text>Item 3</Text>
        <Text>Item 4</Text>
        <Text>Item 5</Text>
        <Text>Item 6</Text>
        <Text>Item 7</Text>  
        <Text>Item 8</Text>
        <Text>Item 9</Text>
        <Text>Item 10</Text>
        <Text>Item 11</Text>
        <Text>Item 12</Text>
        <Text>Item 13</Text>
        <Text>Item 14</Text>
      </ScrollView>
    </View>
    );
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-20
    相关资源
    最近更新 更多