如何从rc-slider第三方组件获取最小值与最大值?附API文档链接
Hey there! Based on your setup with the rc-slider (including the tooltip-enhanced Range), here's how you can easily capture the minimum and maximum values selected:
Step 1: Add State to Track the Selected Range
First, you'll need to use React state to store the current range values. If you're using functional components (the standard approach these days), use the useState hook. For class components, you’d rely on this.state instead.
Step 2: Use the onChange or onAfterChange Event Handler
The rc-slider Range component provides two key events to access selected values:
onChange: Triggers continuously as the slider is dragged (perfect for real-time UI updates)onAfterChange: Triggers only when the user stops dragging (ideal for final actions like form submissions or API calls)
Both events pass an array where the first element is the minimum value and the second is the maximum value of the selected range.
Example Code Snippet
Here’s how to integrate this into your existing code setup:
import 'rc-slider/assets/index.css'; import 'rc-tooltip/assets/bootstrap.css'; import React, { useState } from 'react'; import ReactDOM from 'react-dom'; import Tooltip from 'rc-tooltip'; import Slider from 'rc-slider'; const createSliderWithTooltip = Slider.createSliderWithTooltip; const Range = createSliderWithTooltip(Slider.Range); const App = () => { // Initialize state with your default min/max values (adjust as needed) const [selectedRange, setSelectedRange] = useState([20, 80]); // Handle real-time range updates const handleRangeChange = (value) => { setSelectedRange(value); // Directly extract min and max from the returned array const [minValue, maxValue] = value; console.log(`Current min: ${minValue}, Current max: ${maxValue}`); }; // Handle final range value when dragging stops const handleRangeAfterChange = (value) => { const [finalMin, finalMax] = value; console.log(`Final selected min: ${finalMin}, Final selected max: ${finalMax}`); // Use these values for submissions, calculations, etc. }; return ( <div> <Range min={0} max={100} value={selectedRange} onChange={handleRangeChange} onAfterChange={handleRangeAfterChange} tipFormatter={(value) => `${value}%`} /> {/* Display the current range in your UI */} <p>Selected Range: {selectedRange[0]} - {selectedRange[1]}</p> </div> ); }; ReactDOM.render(<App />, document.getElementById('root'));
Key Notes
- Keep the
valueprop of the Range component synced with your state to maintain controlled component behavior. - For class components, replace the
useStatehook withthis.state = { selectedRange: [20, 80] }and update state usingthis.setState. - The component’s API confirms that the
onChangeandonAfterChangecallbacks receive the range as an array, with the first index being the lower bound and the second the upper bound.
内容的提问来源于stack exchange,提问作者Allu Manikyam

