React组件“ displayName”是做什么用的? [英] What is React component 'displayName' is used for?

查看:1731
本文介绍了React组件“ displayName”是做什么用的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是好的做法,通过添加 displayName 属性来命名组件,但不确定为什么。在react docs中,它说:

I know that is it considered a good practice to name react component by adding a displayName property, but not sure I know why. In react docs, it say:


displayName字符串用于调试消息。 JSX自动设置该值;

The displayName string is used in debugging messages. JSX sets this value automatically; see JSX in Depth.

为什么如此重要?如果我不添加它会怎样? (到目前为止,我还没有它,调试中也没有问题)

Why is is so important? what will happen if I won't add it? (so far I didn't have it and had no issues debugging)

是否有关于如何命名组件的建议/良好做法?

Are there any recommendations / good practices on how to name the components?

推荐答案

我一直将 displayName 设置为与变量相同的名称我将其分配给。它仅在开发版本中使用,因为通过生产版本上的死代码消除将其删除,并且不应在您的应用程序中依赖它。

I have always set displayName to the same name as the variable I am assigning it to. This is would only been used in development builds as it is removed through dead-code elimination on production builds and should not be relied on within your application.

关于使用位置,主要是在响应错误消息中。这就是为什么提到它对于调试很有价值的原因。如果无法导出名称,则错误消息默认为 Component ,如果项目中包含多个组件,则调试起来非常困难。

As for where it is used, that is mainly within react error messaging. This is why it is mentioned to be valuable for debugging. If no name can be derived the error messages default to say Component which is extremely difficult to debug, when you have any more than 1 component in your project.

以下是一些在React源中引用displayName的错误消息:

Here are a few error messages that reference displayName in the react source:

无效的退货

内联样式错误

这篇关于React组件“ displayName”是做什么用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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