【React Native组件】垂直Slider

import React, { useState, useRef } from 'react';
import { Text, View, PanResponder} from 'react-native';

const VIEW_HEIGHT = 300;
const TRACK_HEIGHT = 260;
const THUMB_HEIGHT = 30;
const TRACK_LENGTH = TRACK_HEIGHT - THUMB_HEIGHT;
const MARGIN_VERTICAL = (VIEW_HEIGHT - TRACK_HEIGHT) / 2;

const Slider = (props) => {
  const [currentY, setCurrentY] = useState(MARGIN_VERTICAL);

  const panResponder = useRef(
    PanResponder.create({
      onMoveShouldSetPanResponder: () => true,
      onPanResponderGrant: () => {
         //
      },
      onPanResponderMove: (event, gestureState) => {
         const dy = gestureState.dy;
         const newY = - dy;
         const validY = Math.max(0, Math.min(TRACK_LENGTH , newY));
         setCurrentY(validY + MARGIN_VERTICAL);
      },
      onPanResponderRelease: (event, gestureState) => {
        const dy = gestureState.dy;
        const newY = previousY- dy;
        const validY = Math.max(0, Math.min(TRACK_LENGTH , newY));
        setCurrentY(validY + MARGIN_VERTICAL);
      }
    })
  ).current;
  
  return (
    <View style={{
      flex:1,
      justifyContent:"center",
      alignItems:"center",
      
    }}>

      <View style={{  // Slider
        height:VIEW_HEIGHT,
        width:50,
        borderRadius:15,
        background: "pink",
        justifyContent:"center",
        alignItems:"center",
      }}>
        <View style={{
          width:20,
          height:TRACK_HEIGHT,
          background:"skyblue",
          borderRadius:10,
        }}>
        
        </View>
        
        <View style={{  // thumb
          position:"absolute",
          width:THUMB_HEIGHT,
          height:THUMB_HEIGHT,
          borderRadius:THUMB_HEIGHT / 2,
          bottom: currentY,
          background:"#E4D3E4"
        }}
        {...panResponder.panHandlers}
        >
        </View>
      </View>
    </View>
  );
}

export default Slider;

此代码仅作为封装一个Slider的演示,滑动过程中暂无progress回调。

大家可以在props中加入以下属性以丰富Slider功能:

const {
    onValueChange,
    onSlidingStart,
    onSlidingComplete,
    
    value,
    maxValue,
    minValue,

    containerStyle,
    trackStyle,
    thumbStyle,
} = props;

上一篇:tp批量压缩图片


下一篇:ARM探索之旅 | 二、ARM Cortex-M 用什么指令集?