[英]React scroll element into view
我正在渲染一个日历组件,该组件又基于一个months
数组渲染了一个Month
组件:
{
months.map(month =>
<div style={{marginBottom: "35px"}} key={month}>
<Month
monthName={this.renderMonthName(month)}
daysOfMonth={Object.keys(calendarDays).filter(day => new Date(day).getMonth() === month)}
calendarDays={calendarDays}
year={this.state.year}
/>
</div>
)
}
结果是一整个月的清单:
但是,我要的是,一旦呈现了日历组件,它应该滚动到当前月份(否则用户必须手动向下滚动到当前月份)。
我知道React中的引用,但是我不确定如何在这里应用它。 例如,是否有一种方法可以滚动到每个呈现的Month
组件的键?
不需要复杂的Javascript代码的最佳答案就是这个问题的答案
https://stackoverflow.com/a/49842367/3867490
您可以将其连接到react应用程序的componentDidMount钩子,以便仅在安装组件时运行。
代码在这里,可能很难看,但是您可以从这里得到想法。
class Hello extends React.Component {
constructor(props){
super(props);
this.IsCurrentMonth = this.IsCurrentMonth.bind(this);
this.ScrollToCurrentMonth = this.ScrollToCurrentMonth.bind(this);
this.state = {
months: ['January', 'February','March', 'April', 'May', 'June', 'July', 'August','September', 'October', 'November', 'December'],
currentMonth : new Date().getMonth(),
}
}
componentDidMount(){
this.ScrollToCurrentMonth();
}
IsCurrentMonth(toCompare){
if(this.state.currentMonth === toCompare){
return 'calendar_active';
}
return;
}
ScrollToCurrentMonth(){
var myElement = document.getElementsByClassName('calendar_active')[0];
const y = myElement.getBoundingClientRect().top + window.scrollY;
window.scroll({
top: y,
behavior: 'smooth'
});
}
render() {
return (
<div className={this.state.currentMonth}>
{
this.state.months.map((month, index) =>{
return <div className={`month ${this.IsCurrentMonth(index)}` }>{month}</div>
})
}
</div>
);
}
}
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.