我想用 ref 实现在此组件外部单击按钮时打开 react-datepicker 日历。如果它在条件渲染之外,它工作正常。如果我输入条件语句,我会得到 TypeError:this.calendarRef.current 为 null。它是类组件,并且 calendarRef 在构造函数中定义。
import React from 'react';
import Grid from '@material-ui/core/Grid';
import Button from '@material-ui/core/Button';
import DatePicker from "react-datepicker";
const MyCustomDatePicker = React.forwardRef((props, ref) => (
<DatePicker
ref={ref}
selected={new Date()}
popperPlacement="bottom-start"
monthsShown={2}
/>
));
class DateRangeCustom extends React.Component {
constructor(props) {
super(props);
this.state = {
currentDate: '01/12/2021',
ddCalendarOn: false,
endDate: '08/12/2021',
};
this.calendarRef = React.createRef();
}
handleCalendarBtnClick = () => {
console.log('*** HANDLE CALENDAR BTN ***');
this.setState((state) => ({
ddCalendarOn: !state.ddCalendarOn
}));
this.calendarRef.current.setOpen(true);
}
render() {
console.log('*** render ****')
return (
<Grid container>
<Grid>
<Grid container direction="column">
<Button
onClick={this.handleCalendarBtnClick}
>
SHOW
</Button>
{this.state.ddCalendarOn && <MyCustomDatePicker
ref={this.calendarRef}
/>}
</Grid>
</Grid>
</Grid>
);
}
}
export default DateRangeCustom;
谢谢你的任何建议。