React 组件 'displayName' 是做什么用的?
What is React component 'displayName' is used for?
我知道这是 it considered a good practice 通过添加 displayName
属性 来命名 React 组件,但不确定我知道为什么。在反应文档中,它说:
The displayName string is used in debugging messages. JSX sets this value automatically; see JSX in Depth.
为什么如此重要?如果我不添加它会怎样? (到目前为止我还没有,也没有调试问题)
对于如何命名组件,是否有任何建议/良好做法?
我总是将 displayName
设置为与我分配给它的变量相同的名称。这将用于开发构建,因为它已通过生产构建中的死代码消除被删除,不应在您的应用程序中依赖。
至于用在什么地方,主要是在react error messaging里面。这就是为什么提到它对调试很有价值的原因。如果无法导出名称,则错误消息默认为 Component
,当您的项目中有超过 1 个组件时,这将非常难以调试。
以下是一些在 React 源中引用 displayName 的错误消息:
这篇文章对我有帮助:
How do I get string name of React Native component class?
class CardGroup extends Component {
render() {
return (
<div>{this.props.children}</div>
)
}
}
CardGroup.propTypes = {
children: function (props, propName, componentName) {
const prop = props[propName]
let error = null
React.Children.forEach(prop, function (child) {
if (child.type !== Card) {
error = new Error('`' + componentName + '` children should be of type `Card`.');
}
})
return error
}
}
React documentation 非常清楚它的用途和使用时间。
在大多数情况下,您不需要设置 displayName
,因为它是从 function/class 名称推断出来的。
我知道这是 it considered a good practice 通过添加 displayName
属性 来命名 React 组件,但不确定我知道为什么。在反应文档中,它说:
The displayName string is used in debugging messages. JSX sets this value automatically; see JSX in Depth.
为什么如此重要?如果我不添加它会怎样? (到目前为止我还没有,也没有调试问题)
对于如何命名组件,是否有任何建议/良好做法?
我总是将 displayName
设置为与我分配给它的变量相同的名称。这将用于开发构建,因为它已通过生产构建中的死代码消除被删除,不应在您的应用程序中依赖。
至于用在什么地方,主要是在react error messaging里面。这就是为什么提到它对调试很有价值的原因。如果无法导出名称,则错误消息默认为 Component
,当您的项目中有超过 1 个组件时,这将非常难以调试。
以下是一些在 React 源中引用 displayName 的错误消息:
这篇文章对我有帮助:
How do I get string name of React Native component class?
class CardGroup extends Component {
render() {
return (
<div>{this.props.children}</div>
)
}
}
CardGroup.propTypes = {
children: function (props, propName, componentName) {
const prop = props[propName]
let error = null
React.Children.forEach(prop, function (child) {
if (child.type !== Card) {
error = new Error('`' + componentName + '` children should be of type `Card`.');
}
})
return error
}
}
React documentation 非常清楚它的用途和使用时间。
在大多数情况下,您不需要设置 displayName
,因为它是从 function/class 名称推断出来的。