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

问题描述 投票:0回答:1

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

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的滚动,因此活动歌曲将始终自动更改滚动条的位置使它可见。最好的方法是什么?

javascript reactjs scrollbar audio-player
1个回答
0
投票

我已经使用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

热门问题
推荐问题
最新问题