反应。如何实现滚动到活动列表项?

React. How to implement scrolling to active list item?

我通过艺术家搜索构建音乐播放器。

CODE SANDBOX

这是我的 SongsList 组件的样子:

    const SongsList = (props) => {
  const {
    loading,
    errorMessage,
    songsList,
    toggleActive,
    setToggleActive,
  } = props;
  return (
    <div className='player-list'>
      <div className='songs__list'>
        {loading && !errorMessage ? (
          <span>Loading...</span>
        ) : errorMessage ? (
          <div className='errorMessage'>{errorMessage}</div>
        ) : (
          songsList.map((song, index) => (
            <Song
              key={`${index}`}
              song={song}
              index={index}
              active={toggleActive === index}
              setToggleActive={() => {
                setToggleActive(index);
                // console.log(toggleActive);
              }}
            />
          ))
        )}
      </div>
    </div>
  );
};

现在我想实现基于activeSong位置滚动SongList,这样active歌曲总是会自动改变滚动条位置 使其可见。执行此操作的最佳方法是什么?

我已经使用单首歌曲的 ref 解决了这个问题

  const SongsList = (props) => {

...

const refs = songsList.reduce((song, value) => {
    song[value.id] = React.createRef();
    return song;
  }, {});

...

和方法调用 scrollIntoView

 const handleClick = id =>
    refs[id].current.scrollIntoView({
      behavior: "smooth",
      block: "start"
    });

...

然后在 Song.js 组件中添加这个 scroll() 方法

const Song = ({...}) => {
  const scroll = () => (active ? scrollView(song.id) : undefined);
  useEffect(() => scroll());

...

CodeSandbox finall resolve