【问题标题】:Get Value clicked in material-ui \ core \ Slider在material-ui\core\Slider中点击获取值
【发布时间】:2021-08-04 02:50:47
【问题描述】:

开发 - 反应。

任务:

显示一条带点的线,表示 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. 或者在使用其他组件时是否有解决方案。

【问题讨论】:

  • console.log 返回什么?

标签: reactjs material-ui slider


【解决方案1】:

试试这个:

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>
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 2021-07-05
    相关资源
    最近更新 更多