在 React 页面上显示后如何滚动到组件?
How to scroll to a component after it's shown on the page on React?
我需要在组件呈现到页面后滚动到该组件(我正在使用 React scroll to component)。默认情况下不显示组件本身(组件将在 example_shown
为 true
时呈现)。像这样:
{props.example_shown && (
<ExtraComponent />
)}
在 ExtraComponent
里面,我给出 ref={(section) => { this.ExtraComponent = section }}
。
我试图在 componentDidMount()
中调用 scrollToComponent
,但 this.ExtraComponent
returns 到 null
。我怎样才能滚动到位置?理想情况下 componentDidMount()
应该可以吗?我一直在阅读有关生命周期的内容,但无法解决。我错过了什么?
找到答案!
componentDidMount() {
var elementWhereIwantToScrollTo = ReactDOM.findDOMNode(this)
scrollToComponent(elementWhereIwantToScrollTo, { offset: 0, align: 'middle', duration: 500, ease: 'inCirc' })
}
然后在渲染上,我指定:
<CardBox
ref={(section) => { this.elementWhereIwantToScrollTo = section }}
>
我需要在组件呈现到页面后滚动到该组件(我正在使用 React scroll to component)。默认情况下不显示组件本身(组件将在 example_shown
为 true
时呈现)。像这样:
{props.example_shown && (
<ExtraComponent />
)}
在 ExtraComponent
里面,我给出 ref={(section) => { this.ExtraComponent = section }}
。
我试图在 componentDidMount()
中调用 scrollToComponent
,但 this.ExtraComponent
returns 到 null
。我怎样才能滚动到位置?理想情况下 componentDidMount()
应该可以吗?我一直在阅读有关生命周期的内容,但无法解决。我错过了什么?
找到答案!
componentDidMount() {
var elementWhereIwantToScrollTo = ReactDOM.findDOMNode(this)
scrollToComponent(elementWhereIwantToScrollTo, { offset: 0, align: 'middle', duration: 500, ease: 'inCirc' })
}
然后在渲染上,我指定:
<CardBox
ref={(section) => { this.elementWhereIwantToScrollTo = section }}
>