[英]React how to keep rendered components
I am making a grid using divs in React.我正在 React 中使用div制作网格。 My
Main
component has a Settings
component and a Boxes
component.我的
Main
组件有一个Settings
组件和一个Boxes
组件。
Changing the value inside Settings
will update a state value inside Main
, which is passed to Boxes
.更改
Settings
的值将更新Main
的状态值,该值传递给Boxes
。 Updating this value inside Settings
will cause Boxes
to rerender because it uses the state value of Main
.在
Settings
更新此值将导致Boxes
重新渲染,因为它使用Main
的状态值。
Since the amount of boxes doesn't change, I would like to only change the width and height of each individual box with JavaScript.由于框的数量不会改变,我只想用 JavaScript 更改每个单独框的宽度和高度。 Re rendering isn't necessary in this case.
在这种情况下不需要重新渲染。
I've tried to implement my width/height changing code in shouldComponentUpdate
but this makes it so the boxes don't render at all and throws this error: Warning: Boxes.shouldComponentUpdate(): Returned undefined instead of a boolean value.我试图在
shouldComponentUpdate
实现我的宽度/高度更改代码,但这使得框根本不呈现并引发此错误:警告:Boxes.shouldComponentUpdate():返回未定义而不是布尔值。 Make sure to return true or false.确保返回 true 或 false。
So my question is: how can i keep these boxes rendered without having to re render, since updating the column count will only change width and height of each box?所以我的问题是:如何保持渲染这些框而不必重新渲染,因为更新列数只会改变每个框的宽度和高度?
Current implementation of shouldComponentUpdate: shouldComponentUpdate 的当前实现:
shouldComponentUpdate() {
let boxSize = this.state.wrapperWidth / this.props.columns;
document.styleSheets[1].cssRules[0].style.setProperty('width', boxSize+"px", null);
document.styleSheets[1].cssRules[0].style.setProperty('height', boxSize+"px", null);
}
Whenever a component receives props, it will render again.每当一个组件收到 props 时,它就会再次渲染。 So when the state of your
Main
component is changed, it will trigger a render of Main
which will inevitably pass props to Boxes
and will trigger a render.因此,当
Main
组件的状态发生更改时,它将触发Main
的渲染,这将不可避免地将 props 传递给Boxes
并触发渲染。
However you can use PureCompoonent
to prevent rendering a component if the new props it received is the same as old props.但是,如果组件接收到的新道具与旧道具相同,您可以使用
PureCompoonent
来阻止渲染该组件。
PureComponent does a shallow comparison of previous props and prevents re-render if the props are not changed. PureComponent 对之前的 props 进行浅层比较,并在 props 没有改变的情况下防止重新渲染。
import React, { PureComponent } from 'react';
class Boxes extends PureComponent {
... your commponent code
}
You can read more on PureComponent here - Official React Docs - PureComponent您可以在此处阅读有关 PureComponent 的更多信息 -官方 React 文档 - PureComponent
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.