正如 CWSites 所提到的,一旦您的组件安装(使用componentDidMount
)或在onWidthChange()
回调中(如果您使用该ResponsiveGridLayout
组件),您可以执行以下操作:
import { Responsive, WidthProvider } from 'react-grid-layout';
const ResponsiveGridLayout = WidthProvider(Responsive);
class MyResponsiveGrid extends React.Component {
initialBreakpoint = null;
onWidthChange = width => {
if (this.initialBreakpoint === null) {
// The very first time.
// Compute the initial breakpoint.
const breakpoints = this.props.breakpoints;
const sortedBreakpoints = Object.keys(breakpoints).sort(
(breakpoint1, breakpoint2) =>
breakpoints[breakpoint1] - breakpoints[breakpoint2]
);
let breakpoint = sortedBreakpoints[0];
for (let i = 0; i < sortedBreakpoints.length; i++) {
const currentBreakpoint = sortedBreakpoints[i];
const nextBreakpoint = sortedBreakpoints[i + 1];
if (
typeof nextBreakpoint === "undefined" ||
(breakpoints[currentBreakpoint] <= width &&
width <= breakpoints[nextBreakpoint])
) {
breakpoint = currentBreakpoint;
break;
}
}
this.initialBreakpoint = breakpoint;
// Call your method.
this.props.updateBreakpointKey(this.initialBreakpoint)
}
}
render() {
// E.g.: {lg: layout1, md: layout2, ...}
const layouts = this.props.layouts;
// E.g.: {lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0}
const breakpoints = this.props.breakpoints;
// E.g.: {lg: 12, md: 10, sm: 6, xs: 4, xxs: 2}
const cols = this.props.cols;
return (
<ResponsiveGridLayout layouts={layouts}
breakpoints={breakpoints}
cols={cols}
onBreakpointChange={breakpoint => this.props.updateBreakpointKey(breakpoint)}
onWidthChange={this.onWidthChange}>
{this.props.children}
</ResponsiveGridLayout>
)
}
}