栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何滚动到元素?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何滚动到元素?

React 16.8 +,功能组件

import React, { useRef } from 'react'const scrollToRef = (ref) => window.scrollTo(0, ref.current.offsetTop)   // General scroll to element functionconst ScrollDemo = () => {   const myRef = useRef(null)   const executeScroll = () => scrollToRef(myRef)   return (      <>          <div ref={myRef}>I wanna be seen</div>          <button onClick={executeScroll}> Click to scroll </button>       </>   )}

单击此处,获得有关StackBlits的完整演示

React 16.3 +,Class组件

class ReadyToScroll extends Component {    constructor(props) {        super(props)        this.myRef = React.createRef()      }    render() {        return <div ref={this.myRef}></div>     }    scrollToMyRef = () => window.scrollTo(0, this.myRef.current.offsetTop)       // run this method to execute scrolling.}

类组件-Ref回调

class ReadyToScroll extends Component {    myRef=null    // Optional    render() {        return <div ref={ (ref) => this.myRef=ref }></div>    }    scrollToMyRef = () => window.scrollTo(0, this.myRef.offsetTop)    // run this method to execute scrolling. }

不要使用字符串引用。

字符串引用会损害性能,不可组合且即将淘汰(2018年8月)。

字符串引用存在一些问题,被认为是旧问题,并且很可能在将来的版本之一中删除。[官方React文档]

资源1

资源2

可选:平滑滚动动画

html {    scroll-behavior: smooth;}

将ref传递给孩子

我们希望ref附加到dom元素上,而不是附加到react组件上。因此,当将其传递给子组件时,我们无法命名prop ref。

const MyComponent = () => {    const myRef = useRef(null)    return <ChildComp refProp={myRef}></ChildComp>}

然后将ref prop附加到dom元素。

const ChildComp = (props) => {    return <div ref={props.refProp} />}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/383460.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号