简体   繁体   English

React-Grid-Layout:如何在调整大小时重新渲染项目

[英]React-Grid-Layout: How to re-render items on resize

I am using react-grid-layout and react-custom-scrollbars to create a grid of panels. 我正在使用react-grid-layoutreact-custom-scrollbars来创建面板网格。 Here's a simplifed version of the code: 这是代码的简化版本:

class GridLayoutWithScrollableItems extends React.Component {

    onResize() {
        this.setState({forceRenderAfterResize: Date.now()})
    }

    render() {
        return (
            <ReactGridLayout width={900} onResize={this.onResize.bind(this)}>
                <div key="a">
                    <Scrollbars>
                        <p>Lorem ipsum dolor ....</p>
                    </Scrollbars>
                </div>
                <div key="b">
                    <Scrollbars>
                        <p>Aenean purus magna ...</p>
                    </Scrollbars>
                </div>
            </ReactGridLayout>
        )
    }
}

Works as expected except resizing: Scrollbars will only update its bars when it is re-rendered which is why I am setting that dummy state variable forceRenderAfterResize . 按预期工作,除了调整大小: Scrollbars只会在重新渲染时更新其条形,这就是我设置虚拟状态变量forceRenderAfterResize

What would be the best way to achieve this? 实现这一目标的最佳方法是什么? The solution above feels a bit clumsy and will also re-render all items instead of just the one that was resized. 上面的解决方案感觉有点笨拙,并且还将重新渲染所有项目,而不仅仅是重新调整大小的项目。

Call forceUpdate() in your onResize method. 在onResize方法中调用forceUpdate() Some might try to argue if they've read the react docs incorrectly, that setting state is preferred over forcingUpdate, but that's only when that state is actual state that matters, and setState does not guarantee a re-render if custom shouldComponentUpdate logic is implemented. 有些人可能会试图争论他们是否错误地读取了反应文档,设置状态比forcingUpdate更受欢迎,但只有当该状态是重要的实际状态时才会争用,并且如果自定义了shouldComponentUpdate逻辑,则setState不保证重新呈现。 No reason to muddy your state over UI modifications made via the UI, when you specifically want to re-render if the browser determines a resize: 当您特别想要在浏览器确定调整大小时重新渲染时,没有理由让您的状态混淆通过UI进行的UI修改:

onResize() {
   this.forceUpdate();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM