React点击操作自动定位到另外一个元素


 

使用Ref

方式一

使用ScrollIntoView方法

import React from 'react'

export default class ScrollToElement extends React.Component {
    render() {
        return (
            <div>
                <button onClick={() => {
                    this.refs.targetElement.scrollIntoView()
                }}>点击定位
                </button>
                <div style={{height: '100vh', backgroundColor: 'red'}}>我的</div>
                <input ref='targetElement'/>
            </div>
        )
    }
}

 

方式二

使用window.scrollTo方法

import React from 'react'

export default class ScrollToElement extends React.Component {
    render() {
        return (
            <div>
                <button onClick={() => {
                    {/*this.refs.targetElement.scrollIntoView()*/}
                    window.scrollTo(0, this.refs.targetElement.offsetTop)
                }}>点击定位
                </button>
                <div style={{height: '100vh', backgroundColor: 'red'}}>我的</div>
                <input ref='targetElement'/>
            </div>
        )
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM