在 material-ui \ core \ Slider 中单击获取值

问题描述

开发 - 反应。

任务:

显示一条带有标记 0 到 100 之间百分比的点的线。

数据来自组件之外(出于示例的目的,我创建了一个静态数组)。

价值的数量和价值是动态的。

任务需要点击一个点,为此需要知道点击事件中的哪个点。

我尝试的解决方案:

使用 material-ui\core\Slider。

我禁用了幻灯片功能,以便通过每次更新原始值中的值来使点保持静态。

Slider 中存在的唯一事件是 onChange 它在您单击 Slider 上的任何位置时发生。但是该事件不会返回您单击的位置,而是返回它要计算的新值。通过点击其中一个点,值就会保持不变。

我的代码

import React from 'react';
import { Slider,Tooltip } from '@material-ui/core';

export default function App() {
  
  const marks = [
    { value: 0,label: '0%' },{ value: 100,label: '100%' },];
  
  const ValueLabelComponent = (props) => {
    const { children,open,value } = props;
      return (
          <Tooltip open={open} enterTouchDelay={0} placement="bottom" title={`${value}%`}>
            {children}
          </Tooltip>
      );
  }

  return (
    <div className='container'>
      <Slider
        value={[ 0,5,70,88,93]}
        ValueLabelComponent={ValueLabelComponent}
        track={false}
        onChange={(event,value) => { console.log(event,value) }}
        marks={marks}
      />
    </div>
  );
}

我的问题是:

  1. 有谁知道如何获得按下点的值?

  2. 或者是否有解决方案使用其他组件。

解决方法

试试这个:

import React from 'react';
import { Slider,Tooltip } from '@material-ui/core';

export default function App() {
  
  const marks = [
    // Save the fetched values here instead of under <Slider value=...>
    { value: 0,label: '0%' },{ value: 5,label: '5%' },{ value: 70,label: '70%' },{ value: 88,label: '88%' },{ value: 93,label: '93%' },{ value: 100,label: '100%' },];
  
  const ValueLabelComponent = (props) => {
    const { children,open,value } = props;
      return (
          <Tooltip open={open} enterTouchDelay={0} placement="bottom" title={`${value}%`}>
            {children}
          </Tooltip>
      );
  }

  return (
    <div className='container'>
      <Slider
        ValueLabelComponent={ValueLabelComponent}
        track={false}
        onChange={(event,value) => console.log(`Value of ${value} clicked`) }
        marks={marks}
        steps={null}
      />
    </div>
  );
}