ScrollIntoView()可以找到html元素

ScrollIntoView() can find the html element

我正在尝试创建滚动到元素,但出现此错误

“类型错误:无法读取 属性 'scrollIntoView' 的 null”。 通过控制台记录 mapRef,我可以看到我得到了正确的 div。 console.log

export class FinderComponent extends PureComponent {
  constructor(props) {
    super(props);
    this.mapRef = React.createRef();
  }

  renderMap() {
    return <div block="StoreFinder" ref={this.mapRef}></div>;
  }

  renderStoreCard(store) {
    this.mapRef.current.scrollIntoView({ behavior: "smooth" });
    //console.log(this.mapRef.current);
    return (
      <div
        block="StoreFinder"
        elem="Store"
        key={store_name.replace(/\s/g, "")}
        mods={{ isActive: store_name === selectedStoreName }}
      >
        {this.renderStoreCardContent(store)}
        <button
          block="Button"
          mods={{ likeLink: true }}
          onClick={() => changeStore(store)}
        >
          {__("Show on the map")}
        </button>
      </div>
    );
  }
}

我制作了这个功能组件,它有一个使用 ScrollIntoView() 的工作示例。如果我没理解错的话,您想将 scrollIntoView() 函数添加到一个元素。这是使用功能组件的方式:

import React, { useEffect, useRef } from 'react'

export const TestComponent = () => {
  const inputEl = useRef(null) //"inputEl" is the element that you add the scroll function to

  useEffect(() => {
    inputEl.current.scrollIntoView() //use this if you want the scroll to happen when loading the page
  }, [inputEl])

  const onButtonClick = () => {
    inputEl.current.scrollIntoView() //use this if you want the scroll to happen on click instead.
  }
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  )
}