简体   繁体   English

是否可以在输入 slider 中获取滑块拇指的引用?

[英]Is it possible to get a ref of the slider-thumb in input slider?

I want to apply a tooltips to show the value of the thumb in a range slider.我想应用工具提示来显示 slider 范围内的拇指值。

I know there's a way to do it with calculating the position and such, but I have a pre-build tooltips component that can take the ref and display it at the position.我知道有一种方法可以计算 position 等,但我有一个预构建的工具提示组件,可以获取 ref 并将其显示在 position。

If I get the input ref, the tooltip doesn't move with the thumb and just stay in place in the middle.如果我得到输入参考,工具提示不会随着拇指移动而只是停留在中间的位置。 Is there a way to retrieve the ref for the thumb specifically?有没有办法专门检索拇指的参考?

        <input
          ref={localRef}
          className={'dig-Slider-input'}
          type="range"
          role="slider"
        />

tried getting the local ref of input.尝试获取输入的本地参考。 Needs to get the local ref of thumb.需要获得当地的经验值。

The input element's thumb, also known as the thumb handle, is not a standard HTML element and therefore cannot have a reference assigned to it.输入元素的缩略图(也称为缩略图句柄)不是标准的 HTML 元素,因此无法为其分配引用。 However, you can use JavaScript to dynamically calculate the position of the thumb based on the value of the slider, and then use that information to position your pre-built tooltips component.但是,您可以使用 JavaScript 根据 slider 的值动态计算拇指的 position,然后将该信息用于 position 您预构建的工具提示组件。 You can use the offsetLeft property of the input element and the clientWidth property of the thumb to calculate its position relative to the left edge of the input element.您可以使用输入元素的 offsetLeft 属性和拇指的 clientWidth 属性来计算其相对于输入元素左边缘的 position。

Check below code as an example,以下面的代码为例,

import React, { useRef, useState } from 'react';

const Tooltips = ({ value }) => {
  const inputRef = useRef(null);

  const [thumbPosition, setThumbPosition] = useState(0);

  const handleInputChange = () => {
    const thumb = inputRef.current.querySelector('.thumb');
    const { offsetLeft, clientWidth } = inputRef.current;
    const thumbPosition = (thumb.offsetLeft - offsetLeft) + (clientWidth / 2);
    setThumbPosition(thumbPosition);
  };

  return (
    <div className="slider-container">
      <input
        ref={inputRef}
        className="slider"
        type="range"
        onChange={handleInputChange}
      />
      <div className="tooltip" style={{ left: `${thumbPosition}px` }}>
        {value}
      </div>
    </div>
  );
};

export default Tooltips;

Note: The above code assumes that the thumb handle is styled with a.thumb class.注意:以上代码假定拇指手柄的样式为 a.thumb class。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM