[英]How to avoid to re-render children when updating style via props or state in React?
At the root of my App I have two React components, Menu and Main.在我的应用程序的根目录下,我有两个React组件,Menu 和 Main。 The Menu is hidden by translating it to the left outside of the viewport.
菜单通过将其平移到视口外的左侧来隐藏。 When it is visible, I also want the Main content to translate to the right.
当它可见时,我还希望主要内容向右翻译。 In order to do that I simply pass a menuOpened property (boolean) to both components.
为此,我只需将menuOpened属性(布尔值)传递给两个组件。 It will apply a conditional style that setup the CSS transform property translateX().
它将应用设置 CSS 转换属性 translateX() 的条件样式。 The problem is, when I update the prop, all the children will re-render.
问题是,当我更新道具时,所有的孩子都会重新渲染。 Is there a better practice for changing style of a component depdending of a state / props?
是否有更好的做法来改变状态/道具的组件样式?
As a comment mentioned - a "rerender" is not expensive.正如所提到的评论-“重新渲染”并不昂贵。 Since almost nothing in your DOM tree has changed, the diff is tiny, and so the actual changes are small.
由于 DOM 树中几乎没有任何变化,因此差异很小,因此实际变化很小。
But if you really want to control when a component re-renders, you can use the React life-cycle method shouldComponentUpdate(...)
.但是如果你真的想控制组件何时重新渲染,你可以使用 React 生命周期方法
shouldComponentUpdate(...)
。
You can add an additional class (for example app_with-menu
) to your App container which indicates if the menu is opened or not.您可以向您的 App 容器添加一个额外的类(例如
app_with-menu
),以指示菜单是否已打开。 And then style in CSS like this:然后像这样在 CSS 中设置样式:
.app .content {
// style for content when menu is closed
}
.app.app_with-menu .content {
// style for content when menu is opened
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.