博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

react-native 标题随页面滚动显示和隐藏

Posted on 2019-08-23 11:04  边缘观望  阅读(1300)  评论(0编辑  收藏  举报

效果图如下:

avatar

代码实现:

import React, {Component} from 'react';
import {
    ScrollView,
    Text,
    View,
    FlatList,
} from 'react-native';

export default class Home extends Component {
   
    state = {
        dataObj: [
            {dat: 123},
            {dat: 123},
            {dat: 123},
            {dat: 123},
            {dat: 123},
            {dat: 123},
            {dat: 123},
            {dat: 123},
            {dat: 123},
            {dat: 123},
        ],
    };

    _onScroll(event) {
        let y = event.nativeEvent.contentOffset.y;
        if (y < 250) {
            this.refs.title.setNativeProps({
                style: {
                    opacity: y / 250,
                },
            });
        } else {
            this.refs.title.setNativeProps({
                style: {
                    opacity: 1,
                },
            });
        }
    }

    _keyExtractor = (item, index) => index.toString();

    renderItemView = ({item}) => {
        return <View style={{height: 100}}>
            <Text>{item.dat}</Text>
        </View>;
    };

    render() {
        return (
            <View style={{flex: 1}}>
                <ScrollView
                    scrollEventThrottle={16}
                    onScroll={(event) => this._onScroll(event)}
                    style={{flex: 1}}
                >
                    <View style={{width: '100%', height: 300, backgroundColor: '#8aa5ff'}}/>

                    <FlatList
                        keyExtractor={this._keyExtractor}
                        data={this.state.dataObj}
                        renderItem={this.renderItemView}
                    />
                </ScrollView>
                <View ref='title' style={{
                    height: 50,
                    width: '100%',
                    backgroundColor: '#4aa37c',
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    justifyContent: 'center',
                    alignItems: 'center',
                    opacity: 0,
                }}>
                    <Text style={{color: '#fff', fontSize: 18, fontWeight: 'bold'}}>主&nbsp;页</Text>
                </View>
            </View>
        );
    }
}