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

 

posted @ 2019-02-13 15:48  小橙籽  阅读(2121)  评论(0编辑  收藏  举报