How do I commit the slider's value when the mouse leaves, instead of committing all the values ​​before the mouse leaves?
P粉129731808
P粉129731808 2023-07-27 15:35:18
0
1
391
<p>I have an input field and a slider, the range of the slider is from 1 to 100. Since I also have toggle switches and dropdown menus, I'm using the onChange event for each field instead of using a submit button, including the slider. </p><p>But I ran into a problem, if I try to change the slider from 1 to 50, all the values ​​from 1 to 50 are submitted in the onChange event. I tried using onSlideEnd event but it shows old values ​​(for example: when selecting 50 from 1, it shows 1; when selecting 20 from 50, it shows 50). </p><p>I want that on the change from 1 to 50, only 50 will be sent to the backend in handleSubmit. </p><p>I tried this code but it didn't work, please help to solve it.</p><p><br /></p> <pre class="brush:php;toolbar:false;">import React, { useEffect, useState } from 'react'; import { Slider } from "primereact/slider"; import { InputText } from "primereact/inputtext"; //some imports const Config = () => { const [factorvalue, setFactorValue] = useState(1); const [isSliderDragging, setIsSliderDragging] = useState(false); useEffect(() => { fetchConfig(); }, []); const fetchConfig = async () => { try { // this is used to get config value from backend to set in front const response = await Service.getMaliciousFactorConfig(); if (response) { const maliciousFactorValue = response[0].maliciousFactor || 1; setFactorValue(maliciousFactorValue); } } catch (error) { console.log(error.message); } }; const handleSliderChange = (event) => { try{ const newValue = parseInt(event.value, 10); setFactorValue(newValue); handleSubmit(newValue); }catch(error){ console.log(error); } }; const handleSliderDragEnd = (event) => { setIsSliderDragging(false); }; const handleInputChange = (event) => { const newValue = parseInt(event.target.value, 10); if (!isNaN(newValue)) { setFactorValue(newValue); handleSubmit(newValue); } else { setFactorValue(""); } }; const handleSubmit = async(value) => { try{ if (value >= 1 && value <= 100) { setValidationError(""); await ConfigService.setConfig(value); } }catch(error){ console.log(error); } }; return ( {//demo code} <div className="displayFlex"> <label htmlFor="factor">Factor:</label> <div> <InputText id="factor" value={factorvalue} onChange={handleInputChange} className="w-full" /> <Slider value={factorvalue} onChange={handleSliderChange} onSlideEnd={handleSliderDragEnd} className="w-full" min={1} max={100} /> </div> </div> {//some code} ); }; export default Config;</pre> <p><br /></p>
P粉129731808
P粉129731808

reply all(1)
P粉262926195

Debouncing seems to be the right solution for you. . Read more

There is a React hook available. here.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!