对齐 React Range Slider 的拇指,使其不会超出边界框
Posted
技术标签:
【中文标题】对齐 React Range Slider 的拇指,使其不会超出边界框【英文标题】:Align Thumb of React Range Slider so it doesn't go outside bounding box 【发布时间】:2021-04-22 19:49:02 【问题描述】:我正在尝试制作一个范围滑块,并且我想让拇指(靛蓝)不超出边界框边框(红色)。
如果拇指小,那么它看起来很完美,但如果拇指大,在我的情况下,那么它看起来不对齐。
我在 react-range 库的帮助下使用 React 和 Tailwind,代码如下所示:
import * as React from "react"
import Range from "react-range"
export default function App()
const [values, setValues] = React.useState([50])
return (
<div className="w-full flex justify-center">
<div className="w-48 border-4 border-red-300">
<h1 className="text-4xl">Range</h1>
<label>Slider</label>
<Range
step=1
min=0
max=75
values=values
onChange=(values) =>
setValues(values)
renderTrack=( props, children ) => (
<div
...props
className="w-full h-3 pr-2 my-4 bg-gray-200 rounded-md"
>
children
</div>
)
renderThumb=( props ) => (
<div
...props
className="w-5 h-5 transform translate-x-10 bg-indigo-500 rounded-full focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
/>
)
/>
<span>values[0]px</span>
</div>
</div>
)
我也做了一个可复现的demo→https://codesandbox.io/s/react-tailwind-align-range-slider-ghyf0?file=/src/App.tsx
我希望拇指与Slider
和0px
对齐,否则它看起来不正常。即使是原生范围滑块也不会超出边界框。我怎样才能达到这种效果?
【问题讨论】:
【参考方案1】:我最终使用了react-slider,而不是保留在边界框内。
import * as React from "react"
import Range from "react-range"
import ReactSlider from "react-slider"
export default function App()
const [values, setValues] = React.useState([0])
const [value, setValue] = React.useState(0)
return (
<div className="w-full flex justify-center">
<div className="w-48 border-4 border-red-300">
<h1 className="text-4xl">Range</h1>
<label>React Range</label>
<Range
step=1
min=0
max=75
values=values
onChange=(values) =>
setValues(values)
renderTrack=( props, children ) => (
<div
...props
className="w-full h-3 pr-2 my-4 bg-gray-200 rounded-md"
>
children
</div>
)
renderThumb=( props ) => (
<div
...props
className="w-5 h-5 transform translate-x-10 bg-indigo-500 rounded-full focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
/>
)
/>
<span>values[0]px</span>
<br />
<br />
<hr />
<br />
<label>React Slider</label>
<ReactSlider
step=1
min=0
max=75
className="w-full h-3 pr-2 my-4 bg-gray-200 rounded-md cursor-grab"
thumbClassName="absolute w-5 h-5 cursor-grab bg-indigo-500 rounded-full focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 -top-2px"
value=value
onChange=(value: any) =>
setValue(value)
/>
<span>valuepx</span>
</div>
</div>
)
Codesandbox 上的定位有点偏离,但它通过提供一点绝对定位在我的应用上工作:)
代码沙盒 → https://codesandbox.io/s/react-tailwind-align-range-slider-ghyf0?file=/src/App.tsx
【讨论】:
以上是关于对齐 React Range Slider 的拇指,使其不会超出边界框的主要内容,如果未能解决你的问题,请参考以下文章