0

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

“TypeError:无法读取 null 的属性‘scrollIntoView’”。通过控制台记录 mapRef 我可以看到我得到了正确的 div。 控制台日志

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>
    );
  }
}
4

1 回答 1

1

我制作了这个功能组件,它有一个使用 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>
    </>
  )
}
于 2021-08-30T09:35:10.643 回答