就我的 React 经验而言,我有两种方法可以根据 props/state 从 React 组件输出/渲染中隐藏一些渲染的 HTML:
- 用一些条件逻辑包围有问题的 HTML/JSX,或者
- 有条件地向该元素添加一个类,让 CSS 控制显示/可见性
我想知道哪个是最佳实践?我有一种预感,使用 CSS 方法可能会带来一些性能提升,因为浏览器不需要那么频繁地操作 DOM。 或者,有时从 DOM 中完全删除一个元素会很好。
有什么见解吗?
最佳答案
我问了一个类似的问题,并收到了 React 核心团队成员之一 Sophie Alpert 的回复。
Basically in most cases it's better not to render the HTML at all if it should stay that way throughout the lifetime of that page. If frequent toggling is desired, then use CSS to show/hide the element.
关于javascript - 在 React 中有条件地渲染或有条件地添加一个类来隐藏元素是更好的做法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32885205/