在React.js中隐藏组件的正确方法 [英] Correct way to hide components in React.js

查看:261
本文介绍了在React.js中隐藏组件的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您将一个名为 show 的道具传递给组件。如果prop值为true,则应正常呈现完整组件。如果是假,则不应显示任何内容。

Say you are passing a prop called show to a component. If the prop value is true, you should render the full component normally. If it is false, you should not display anything.

你可以用两种方式做到这一点。

You can do this two ways.


  1. 在组件的render方法中返回null。

  2. 将包含 display:none 属性的CSS类应用于组件的DOM元素。

  1. return null in the render method of the component.
  2. apply a CSS class containing display: none attribute to the component's DOM element.

哪些是正确的或首选的方式?

Which ones is the correct or the preferred way?

推荐答案

在大多数情况下,您的两种解决方案是可以互换的。他们都工作很好。

For the most part, your two solutions are interchangeable. They both "work" fine.

我会警告不要先选择优先选择哪种方法进行优先选择。如果你确实需要最终修改你的代码并尝试其他方法,这是一个荒谬的简单交换,不应该是一个障碍。因此,在有理由担心之前不要担心。

I would warn against preemptive optimization in choosing which of these methods to choose. If you do need to eventually modify your code and try the other method, this is an absurdly simple swap to make and shouldn't be an obstacle. So don't worry about it until there's a reason to worry about it.

这篇关于在React.js中隐藏组件的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆