我想根据浏览器窗口的当前大小设置组件的状态。已经使用服务端渲染(React+Redux)。我正在考虑使用 Redux 商店作为胶水 - 只是为了在调整大小时更新商店。 是否有任何其他/更好的解决方案不涉及 Redux。 谢谢。
class FocalImage extends Component {
// won't work - the backend rendering is used
// componentDidMount() {
// window.addEventListener(...);
//}
//componentWillUnmount() {
// window.removeEventListener('resize' ....);
//}
onresize(e) {
//
}
render() {
const {src, className, nativeWidth, nativeHeight} = this.props;
return (
<div className={cn(className, s.focalImage)}>
<div className={s.imageWrapper}>
<img src={src} className={_compare_ratios_ ? s.tall : s.wide}/>
</div>
</div>
);
}
}
最佳答案
我有一个调整大小的辅助组件,我可以将一个函数传递给它,它看起来像这样:
class ResizeHelper extends React.Component {
static propTypes = {
onWindowResize: PropTypes.func,
};
constructor() {
super();
this.handleResize = this.handleResize.bind(this);
}
componentDidMount() {
if (this.props.onWindowResize) {
window.addEventListener('resize', this.handleResize);
}
}
componentWillUnmount() {
if (this.props.onWindowResize) {
window.removeEventListener('resize', this.handleResize);
}
}
handleResize(event) {
if ('function' === typeof this.props.onWindowResize) {
// we want this to fire immediately the first time but wait to fire again
// that way when you hit a break it happens fast and only lags if you hit another break immediately
if (!this.resizeTimer) {
this.props.onWindowResize(event);
this.resizeTimer = setTimeout(() => {
this.resizeTimer = false;
}, 250); // this debounce rate could be passed as a prop
}
}
}
render() {
return (<div />);
}
}
然后任何需要在调整大小上做某事的组件都可以像这样使用它:
<ResizeHelper onWindowResize={this.handleResize} />
您可能还需要在 componentDidMount 上调用一次传递的函数来设置 UI。由于 componentDidMount 和 componentWillUnmount 永远不会在服务器上被调用,所以这在我的同构应用程序中完美运行。
关于reactjs - React Isomorphic Rendering - 处理窗口调整大小事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40580424/