简体   繁体   English

将滚动元素反应到视图中

[英]React scroll element into view

I am rendering a calendar component, which is again rendering a Month component based on a months array: 我正在渲染一个日历组件,该组件又基于一个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>
  )
}

The result is a long list of single months: 结果是一整个月的清单:

在此处输入图片说明

However, what I want is that once the calendar component is rendered it should scroll to the current month (otherwise users have to scroll down manually to the current month). 但是,我要的是,一旦呈现了日历组件,它应该滚动到当前月份(否则用户必须手动向下滚动到当前月份)。

I know about refs in React but I'm no sure how to apply this here. 我知道React中的引用,但是我不确定如何在这里应用它。 Is there a way to scroll to, let's say, eg the key of each rendered Month component? 例如,是否有一种方法可以滚动到每个呈现的Month组件的键?

Best answer that doesn't need nitty gritty Javascript code is answer from this question 不需要复杂的Javascript代码的最佳答案就是这个问题的答案

https://stackoverflow.com/a/49842367/3867490 https://stackoverflow.com/a/49842367/3867490

You can hook it up at the componentDidMount hook of your react app so it will only run whenever the component was mounted. 您可以将其连接到react应用程序的componentDidMount钩子,以便仅在安装组件时运行。

Code is here, might be ugly but you can get the idea from here. 代码在这里,可能很难看,但是您可以从这里得到想法。

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')
);

See the working fiddle here https://jsfiddle.net/keysl183/f9ohzymd/31/ 在这里查看工作提琴https://jsfiddle.net/keysl183/f9ohzymd/31/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM