react 滚动到指定元素位置,类似锚点功能

组件

class HomeView extends Component {

  scrollToAnchor = (anchorName) => {
    if (anchorName) {
        let anchorElement = document.getElementById(anchorName);
        if(anchorElement) { anchorElement.scrollIntoView(); }
    }
  }

  render() {

    return (
      
be together. not the same.
welcome to android... be yourself. do your thing. see what's going on.
this.scrollToAnchor('screens')}>
跳到这里
); } } export default HomeView;

scrollIntoView的语法

用法如下:
element.scrollIntoView();
element.scrollIntoView(true);
element.scrollIntoView(alignToTop);
element.scrollIntoView(scrollIntoViewOptions);

alignToTop是一个布尔值,true 元素对齐到祖先元素的顶部,false 元素对齐到祖先元素的底部,默认是true
scrollIntoViewOptions是一个布尔值或以下选项的对象:

{
     behavior: 'auto' | 'instant' | 'smooth',
     block: 'start' | 'end'
}

你可能感兴趣的:(react 滚动到指定元素位置,类似锚点功能)