Bar*_*kse 7 date-range reactjs next.js
I'm using DateRangePicker from react-date-range in a next.js project.
You can see the expected behavior on their demo page: if you select any date from the month on the right, the months stay in place. Here's a video.
But in my project, the month from the right jumps to the left on date selection (as you can see it in this video).
I've made a simple demo here by copying code from their demo page:
import { addDays } from "date-fns";
import { useState } from "react";
import { DateRangePicker } from "react-date-range";
import "react-date-range/dist/styles.css"; // main style file
import "react-date-range/dist/theme/default.css"; // theme css file
export default function IndexPage() {
const [state, setState] = useState([
{
startDate: new Date(),
endDate: addDays(new Date(), 7),
key: "selection"
}
]);
return (
<div>
<h1>Hello</h1>
<DateRangePicker
onChange={(item) => setState([item.selection])}
showSelectionPreview={true}
moveRangeOnFirstSelection={false}
months={2}
ranges={state}
direction="horizontal"
/>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
Here you can see the code from my demo page.
Any idea or solution to stop this behavior is welcome! Thank you!
这是一个奇怪的问题 --- 我确信更熟悉 Next.js 的人可以更新此问题以具体说明发生此错误的原因,但现在我已经确定了修复方法和可能的解释。
我将您的代码插入到一个create-react-app实例中,它工作得很好,很有趣:
这里是沙盒。
我测试了您相同的代码并观察到相同的奇怪格式。我还注意到 生成的日期next.js奇怪地不准确;例如,它不会从今天开始(它已经关闭了一个日期,在“明天”开始选择;准确地开始初始选择的版本不是这种情况create-react-app),因此渲染出现了问题。我最好的猜测:next.js可能不会重新渲染<DateRangePicker />和/或其 css 值(或一般的组件?)——至少在组件初始化时不会?——所以我在加载时注入了初始数据选择useEffect并添加了状态的字符串化版本作为容器 div 的键以强制重新渲染,并且它不再显示奇怪的选择 css:
import { addDays } from "date-fns";
import { useState, useEffect } from "react";
import { DateRangePicker } from "react-date-range";
import "react-date-range/dist/styles.css"; // main style file
import "react-date-range/dist/theme/default.css"; // theme css file
export default function App() {
const [state, setState] = useState([]);
useEffect(() => { {/* <---- useEffect to update state on init */}
if (state.length === 0) {
setState([
{
startDate: new Date(),
endDate: addDays(new Date(), 7),
key: "selection"
}
]);
}
}, [state, setState]);
return (
<div key={JSON.stringify(state)}> {/* <-- added key here, to force rerender */}
<h1>Hello</h1>
<DateRangePicker
onChange={(item) => setState([item.selection])}
showSelectionPreview={true}
moveRangeOnFirstSelection={false}
months={2}
ranges={state}
direction="horizontal"
/>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
619 次 |
| 最近记录: |