react-day-picker ref 当前无法访问 scrollIntoView

问题描述

我正在使用 react-day-picker。我想在单击输入后滚动到“日历”-DayPicker 组件(问题是滚动页面时,然后日历不在视口中。我尝试了这种方法(简化):

import React from 'react';
import DayPickerInput from 'react-day-picker/DayPickerInput';

class DatePicker extends React.Component {
    constructor(props) {
        super(props);
        this.fromDayPickerRef = React.createRef();
        this.toDayPickerRef = React.createRef();

        this.handleOnDayPickerShow = ref => { this[ref].current.scrollIntoView() }
    }
    render() {
        const {from,to} = this.state;
        const modifiers = {start: from,end: to};
        return (
            <div className="InputFromTo">
                <DayPickerInput
                    ...
                    dayPickerProps={{
                        ...
                        ref: this.fromDayPickerRef,}}
                    ...
                    onDayPickerShow={() => this.handleOnDayPickerShow("fromDayPickerRef")}
                /><br/>
                <span className="InputFromTo-to">
                    <DayPickerInput
                        ...
                        dayPickerProps={{
                            ...
                            ref: this.toDayPickerRef,}}
                        ...
                        onDayPickerShow={() => this.handleOnDayPickerShow("toDayPickerRef")}
                    />
                </span>
            </div>
    }
}

我可以访问 .current 但没有 HTML DOM 属性(例如 offSetTop)或函数。有什么猜测吗?

解决方法

我想通了。您不能像这样引用函数组件(可以使用 forwardRef)。但是引用稍后会传递给 DOM 元素。您需要通过以下方式进行:

dayPickerProps={{
    ...
    ref: el => {this.fromDayPickerRef = el},}}