在鼠标离开时提交滑块数值,而不是在鼠标离开之前提交所有数值。

huangapple go评论87阅读模式
英文:

how to submit the slider value on mouse leave instead of submitting all values until mouse leave

问题

我有一个输入字段和一个滑块,滑块的范围是从1到100。由于我有切换开关和下拉菜单,我为每个字段都设置了onChange事件,而不是提交按钮,包括滑块。

但是我遇到了一个问题,如果我尝试从1更改滑块到50,所有值都会使用onChange提交,我尝试使用onSlideEnd,但它显示旧值(例如:从1选择50时显示1,从50选择20时显示50)。

我想要的是,当从1更改为50时,只有50应该从handleSubmit发送到后端。

我尝试了这段代码,但不起作用,请帮助

import React, { useEffect, useState } from 'react';
import { Slider } from "primereact/slider";
import { InputText } from "primereact/inputtext";
// 一些导入语句

const Config = () => {

  const [factorvalue, setFactorValue] = useState(1);
  const [isSliderDragging, setIsSliderDragging] = useState(false);

  useEffect(() => {
    fetchConfig();
  }, []);
  
  const fetchConfig = async () => {
    try {
      // 这用于从后端获取配置值以在前端设置
      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 (
          {/* 演示代码 */}
          <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>
		  {/* 一些代码 */}
  );
};

export default Config;
英文:

i have a input field and slider which has range between 1 to 100.
since i have toggle switches and drop downs i keep onChange events for each field instead of submit button including for slider also.

but i am facing an issue if i try to change slider from 1 to 50 all values upto 50 are submitting using onChange and i tried to use onSlideEnd but it showing old value (ex: showing 1 when selecting 50 from 1 and showing 50 when selecting 20 from 50).

i want it like while changing from 1 to 50 only 50 should send to back end from handleSubmit

i tried this code but not working please help

import React, { useEffect, useState } from &#39;react&#39;;
import { Slider } from &quot;primereact/slider&quot;;
import { InputText } from &quot;primereact/inputtext&quot;;
//some imports
const Config = () =&gt; {
const [factorvalue, setFactorValue] = useState(1);
const [isSliderDragging, setIsSliderDragging] = useState(false);
useEffect(() =&gt; {
fetchConfig();
}, []);
const fetchConfig = async () =&gt; {
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) =&gt; {
try{
const newValue = parseInt(event.value, 10);
setFactorValue(newValue);
handleSubmit(newValue);
}catch(error){
console.log(error);
}
};
const handleSliderDragEnd = (event) =&gt; {
setIsSliderDragging(false);
};
const handleInputChange = (event) =&gt; {
const newValue = parseInt(event.target.value, 10);
if (!isNaN(newValue)) {
setFactorValue(newValue);
handleSubmit(newValue);
} else {
setFactorValue(&quot;&quot;);
}
};
const handleSubmit = async(value) =&gt; {
try{
if (value &gt;= 1 &amp;&amp; value &lt;= 100) {
setValidationError(&quot;&quot;);
await ConfigService.setConfig(value);
}
}catch(error){
console.log(error);
}
};
return (
{//demo code}
&lt;div className=&quot;displayFlex&quot;&gt;
&lt;label htmlFor=&quot;factor&quot;&gt;Factor:&lt;/label&gt;
&lt;div&gt;
&lt;InputText id=&quot;factor&quot; value={factorvalue} onChange={handleInputChange} className=&quot;w-full&quot; /&gt;
&lt;Slider value={factorvalue} onChange={handleSliderChange} onSlideEnd={handleSliderDragEnd} className=&quot;w-full&quot; min={1} max={100} /&gt;
&lt;/div&gt;
&lt;/div&gt;
{//some code}
);
};
export default Config;

答案1

得分: 1

你正在朝着正确的方向思考。按照以下步骤进行操作以使其正常工作(假设你希望在 onSlideEnd 触发时提交):

  1. 在滑块变化时,更新 fractionValue,但不要调用 handleSubmit
  2. onSlideEnd 中调用 handleSubmit
<Slider value={factorvalue} onChange={handleSliderChange} onSlideEnd={() => handleSubmit(factorvalue)} className="w-full" min={1} max={100} />
英文:

You are thinking in right direction. Follow these steps to get it working (Assuming that you want to submit when onSlideEnd fires)

  1. onSlider change, update the fractionValue, however don't call handleSubmit.
  2. Call handleSubmit in onSlideEnd
&lt;Slider value={factorvalue} onChange={handleSliderChange} onSlideEnd={()=&gt; handleSubmit(factorvalue)} className=&quot;w-full&quot; min={1} max={100} /&gt;

答案2

得分: 0

我试过这样,对我有用

import React, { useEffect, useState, useRef } from 'react';
import { Slider } from "primereact/slider";
import { InputText } from "primereact/inputtext";
//一些导入

const Config = () => {

  const [factorvalue, setFactorValue] = useState(1);
  const factorValueRef = useRef(1);
  const [isSliderDragging, setIsSliderDragging] = useState(false);

  useEffect(() => {
    fetchConfig();
  }, []);

  const fetchConfig = async () => {
    try {
      // 这用于从后端获取配置值以在前端设置
      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);
      factorValueRef.current = newMaliciousFactor;
    }catch(error){
      console.log(error);
    }
  };

  const handleSliderDragEnd = (event) => {
    setIsSliderDragging(false);
    handleSubmit(factorValueRef.current);
  };

  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;
英文:

i tried like this and worked for me

import React, { useEffect, useState,useRef} from &#39;react&#39;;
import { Slider } from &quot;primereact/slider&quot;;
import { InputText } from &quot;primereact/inputtext&quot;;
//some imports
const Config = () =&gt; {
const [factorvalue, setFactorValue] = useState(1);
const factorValueRef = useRef(1);
const [isSliderDragging, setIsSliderDragging] = useState(false);
useEffect(() =&gt; {
fetchConfig();
}, []);
const fetchConfig = async () =&gt; {
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) =&gt; {
try{
const newValue = parseInt(event.value, 10);
setFactorValue(newValue);
factorValueRef.current = newMaliciousFactor;
}catch(error){
console.log(error);
}
};
const handleSliderDragEnd = (event) =&gt; {
setIsSliderDragging(false);
handleSubmit(factorValueRef.current);
};
const handleInputChange = (event) =&gt; {
const newValue = parseInt(event.target.value, 10);
if (!isNaN(newValue)) {
setFactorValue(newValue);
handleSubmit(newValue);
} else {
setFactorValue(&quot;&quot;);
}
};
const handleSubmit = async(value) =&gt; {
try{
if (value &gt;= 1 &amp;&amp; value &lt;= 100) {
setValidationError(&quot;&quot;);
await ConfigService.setConfig(value);
}
}catch(error){
console.log(error);
}
};
return (
{//demo code}
&lt;div className=&quot;displayFlex&quot;&gt;
&lt;label htmlFor=&quot;factor&quot;&gt;Factor:&lt;/label&gt;
&lt;div&gt;
&lt;InputText id=&quot;factor&quot; value={factorvalue} onChange={handleInputChange} className=&quot;w-full&quot; /&gt;
&lt;Slider value={factorvalue} onChange={handleSliderChange} onSlideEnd={handleSliderDragEnd} className=&quot;w-full&quot; min={1} max={100} /&gt;
&lt;/div&gt;
&lt;/div&gt;
{//some code}
);
};
export default Config;

答案3

得分: -1

Debouncing seems to be the right solution for you.

一个 React hook 可在这里找到。

安装该 hook:npm i @uidotdev/usehooks

如何使用该 hook:

const [sliderValue, setSliderValue] = useState(0);
const debouncedValue = useDebounce(sliderValue, 500);
useEffect(() => submit(debouncedValue), [debouncedValue]);

这将等待 sliderValue 在 0.5 秒内未更改,然后使用该值调用 submit。

英文:

Debouncing looks like the right solution for you. Read more

A react-hook is available here.

Install the hook: npm i @uidotdev/usehooks

How to use the hook:

const [sliderValue, setSliderValue] = useState(0);
const debouncedValue = useDebounce(sliderValue, 500);
useEffect(()=&gt;submit(debouncedValue),[debouncedValue])

This will wait until sliderValue hasn't changed 0.5 seconds and then call submit with the value.

huangapple
  • 本文由 发表于 2023年7月18日 16:31:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76710872.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定