簡體   English   中英

將滾動元素反應到視圖中

[英]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')
);

在這里查看工作提琴https://jsfiddle.net/keysl183/f9ohzymd/31/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM