【问题标题】:Control the material-ui slider with a play and stop buttons in React JS在 React JS 中使用播放和停止按钮控制 material-ui 滑块
【发布时间】:2021-04-07 09:55:06
【问题描述】:

我在 ReactJS 项目中使用 metrial-ui 中的连续滑块。我想控制滑块,当点击播放按钮时,滑块开始移动,点击停止时停止。下面是滑块的代码。

   const useStyles = makeStyles({
  root: {
    width: 200,
  },
});
         
<div className={classes.root}>
      <Typography id="continuous-slider" gutterBottom>
        Volume
      </Typography>
      <Grid container spacing={2}>
        <Grid item>
          <VolumeDown />
        </Grid>
        <Grid item xs>
          <Slider value={value} onChange={handleChange} aria-labelledby="continuous-slider" />
        </Grid>
        <Grid item>
          <VolumeUp />
        </Grid>
      </Grid>

提前致谢

【问题讨论】:

    标签: javascript reactjs react-hooks material-ui


    【解决方案1】:

    这可以通过调用setState 在间隔后更新Slider 值来完成。当isRunning 状态发生变化时,您需要使用useEffect 创建和清理间隔回调:

    export default function ContinuousSlider() {
      const [value, setValue] = useState<number>(30);
      const [isRunning, setIsRunning] = useState(false);
      const directionRef = useRef<"back" | "forward">("back");
      const intervalIdRef = useRef(0);
    
      const handleChange = (event: any, newValue: number | number[]) => {
        setValue(newValue as number);
      };
      const handleBack = () => {
        directionRef.current = "back";
        if (!isRunning) {
          setIsRunning(true);
        }
      };
      const handleNext = () => {
        directionRef.current = "forward";
        if (!isRunning) {
          setIsRunning(true);
        }
      };
      const handleStop = () => {
        setIsRunning((r) => !r);
      };
    
      useEffect(() => {
        if (isRunning) {
          intervalIdRef.current = setInterval(() => {
            if (directionRef.current === "forward") {
              setValue((v) => ++v);
            }
            if (directionRef.current === "back") {
              setValue((v) => --v);
            }
          }, 16);
        }
    
        return () => clearInterval(intervalIdRef.current);
      }, [isRunning]);
    
      return (
        <>
          <IconButton onClick={handleStop}>
            <StopIcon />
          </IconButton>
          <IconButton onClick={handleBack}>
            <ArrowBackIcon />
          </IconButton>
          <IconButton onClick={handleNext}>
            <ArrowForwardIcon />
          </IconButton>
          <Slider value={value} onChange={handleChange} />
        </>
      );
    }
    

    现场演示

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-17
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      • 2012-08-27
      • 2022-08-24
      • 2019-10-13
      • 2015-12-14
      相关资源
      最近更新 更多