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

猜你喜欢

转载自www.cnblogs.com/xiaochengzi/p/10370189.html