react-slider实现彩色可拖动滑块
先说明下需求:-UI设计如图(需要实现的效果):可拖动滑块,对应百分比,以及对应css宽度。
实现步骤:
第一步:npm下载安装react-slider: npm install --save rc-slider
第二步:组件页面引入:
import Slider, { Range } from "rc-slider";
import "rc-slider/assets/index.css";
第三步:关键代码:
import { useState, useEffect } from "react"; import Slider, { Range } from "rc-slider"; import "rc-slider/assets/index.css"; // 实现两端固定,中间3个点可拖动,需将中间三个点的值可控,两端的值用value写死 const [sValue, setSValue] = useState(40); const [sValue1, setSValue1] = useState(60); const [sValue2, setSValue2] = useState(80); // 对应百分比 列表 const [percentList, setPercentList] = useState([40, 20, 20, 20]); // 滑动滑块触发 const onSliderChange = (value: any) => { for (let i = 0; i < value.length; i++) { setSValue(value[1]); setSValue1(value[2]); setSValue2(value[3]); } addPercent(value); }; // 计算滑块百分比 const addPercent = (value: any) => { let opt: any = []; for (let i = 0; i < value.length; i++) { opt.push( value[1], value[2] - value[1], value[3] - value[2], value[4] - value[3] ); } setPercentList(opt.slice(16, 20)); return opt.slice(16, 20); }; return ( <div className="color-progress"> // 显示百分比 <div className="color-slider-contain"> {percentList.map((v, k) => { return ( <div className="color-slider-label" key={k} style={{ width: v + "%" }} > {v}% </div> ); })} </div> // 显示彩色滑块 <Range count={3} defaultValue={[0, 40, 50, 60, 100]} value={[0, sValue, sValue1, sValue2, 100]} pushable trackStyle={[ { backgroundColor: "#4368ec" }, { backgroundColor: "#49c8ed" }, { backgroundColor: "#eea844" }, { backgroundColor: "#eee044" }, ]} handleStyle={[ { backgroundColor: "#4368ec" }, { backgroundColor: "#4368ec" }, { backgroundColor: "#49c8ed" }, { backgroundColor: "#eea844" }, { backgroundColor: "#eee044" }, ]} railStyle={{ backgroundColor: "#0c0d30" }} onChange={onSliderChange} /> </div> ) // css .color-progress { width: 41vw; margin-left: 2vw; height: 10vh; display: flex; align-items: center; justify-content: center; flex-direction: column; .rc-slider { margin: 0.7vh 0 1vh; } .rc-slider-track { height: 8px; } .rc-slider-handle { width: 18px; height: 18px; border: 2px solid #ffffff; } .color-slider-contain { width: 100%; height: 2.5vh; color: #d9d9d9; display: flex; .color-slider-label { color: #d9d9d9; text-align: center; } } }
第四步:附上api:
https://slider-react-component.vercel.app/demo/range
https://slider-react-component.vercel.app/