What is React component 'displayName' is used for?

▼魔方 西西 提交于 2020-08-02 05:38:06

问题


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:

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?


回答1:


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.

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.

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

Invalid Return

Inline style error




回答2:


this article helped me:

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
      }
    }


来源:https://stackoverflow.com/questions/41581130/what-is-react-component-displayname-is-used-for

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!