0

我试图用反应钩子构建一个音频进度条。我正在关注基于反应类的组件的教程,但对 refs 有点迷失。

当页面加载时,如何为我的 useRef 变量提供 div ref 的初始值?

一旦我开始玩,我就会收到一个错误,说无法读取 null 的偏移宽度。显然时间轴 ref 为空,因为它没有初始值。如何在 useEffect 挂钩中将其连接到具有时间轴 ID 的 div?

const AudioPlayer = () => {
  const url = "audio file";

  const [audio] = useState(new Audio(url));
  const [duration, setDuration] = useState(0);
  const [currentTime, setCurrentTime] = useState(0)
  let timelineRef = useRef()
  let handleRef = useRef()

  useEffect(() => {
    audio.addEventListener('timeupdate', e => {
      setDuration(e.target.duration);
      setCurrentTime(e.target.currentTime)
      let ratio = audio.currentTime / audio.duration;
      let position = timelineRef.offsetWidth * ratio;
      positionHandle(position);
    })
  }, [audio, setCurrentTime, setDuration]);



  const mouseMove = (e) => {
    positionHandle(e.pageX);
    audio.currentTime = (e.pageX / timelineRef.offsetWidth) * audio.duration;
  };

  const mouseDown = (e) => {
    window.addEventListener('mousemove', mouseMove);
    window.addEventListener('mouseup', mouseUp);
  };

  const mouseUp = (e) => {
    window.removeEventListener('mousemove', mouseMove);
    window.removeEventListener('mouseup', mouseUp);
  };

  const positionHandle = (position) => {
    let timelineWidth = timelineRef.offsetWidth - handleRef.offsetWidth;
    let handleLeft = position - timelineRef.offsetLeft;
    if (handleLeft >= 0 && handleLeft <= timelineWidth) {
      handleRef.style.marginLeft = handleLeft + "px";
    }
    if (handleLeft < 0) {
      handleRef.style.marginLeft = "0px";
    }
    if (handleLeft > timelineWidth) {
      handleRef.style.marginLeft = timelineWidth + "px";
    }
  };


  return (
    <div>

      <div id="timeline" ref={(timeline) => { timelineRef = timeline  }}>
      <div id="handle" onMouseDown={mouseDown} ref={(handle) => { handleRef = handle }} />
      </div>
    </div> 
  )
}
4

1 回答 1

2

useRef()钩子返回对对象的引用,带有属性current。该current属性是useRef指向的实际值。

要使用引用,只需在元素上设置它:

<div id="timeline" ref={timelineRef}>
<div id="handle" onMouseDown={mouseDown} ref={handleRef} />

然后要使用它,您需要引用该current属性:

let position = current.timelineRef.offsetWidth * ratio;

而且positionHandle- 你不应该以这种方式在 React 中的元素上设置样式。使用setState()钩子,并使用 JSX 设置样式。

const positionHandle = (position) => {
  let timelineWidth = timelineRef.current.offsetWidth - handleRef.current.offsetWidth;
  let handleLeft = position - timelineRef.current.offsetLeft;
  if (handleLeft >= 0 && handleLeft <= timelineWidth) {
      handleRef.current.style.marginLeft = handleLeft + "px";
  }
  if (handleLeft < 0) {
    handleRef.current.style.marginLeft = "0px";
  }
  if (handleLeft > timelineWidth) {
    handleRef.current.style.marginLeft = timelineWidth + "px";
  }
};

此外,ref 还可以用于其他值,例如new Audio(url), 并从current属性中提取:

const { current: audio } = useRef(new Audio(url));
于 2020-03-27T18:56:23.883 回答