Get component name in React

前端 未结 5 1923
暗喜
暗喜 2020-12-05 18:08

I\'m developing a React application. I have a Loading component, which is a little animation for waiting. I want to add a message in this Loading component according to the

相关标签:
5条回答
  • 2020-12-05 18:35

    After searching with debugger, in newer versions you should use this._reactInternalFiber.elementType.name instead of this._reactInternalInstance.getName()

    0 讨论(0)
  • 2020-12-05 18:44

    For HOCs: you can use WrappedComponent.name

    0 讨论(0)
  • 2020-12-05 18:51

    You don't need it to be dynamic since you are writing the component yourself and can pass it as a string

    class LoginForm extends React.Component {
        render() {   
            return (
                <div className="login-form-root">
                     {this.state.displayLoading && <Loading loadingFrom="LoginForm "/>}
                </div>
            );
        }
    }
    

    However if you still need to access the name of the component, you could define the displayName property on the component

    class LoginForm extends React.Component {
       static displayName = 'LoginForm';
        render() {   
            return (
                <div className="login-form-root">
                     {this.state.displayLoading && <Loading loadingFrom="LoginForm "/>}
                </div>
            );
        }
    }
    

    and access it like Component.displayName.

    0 讨论(0)
  • 2020-12-05 18:53

    Every React.Component has a property called displayName that JSX sets automatically, so theoretically you can use that property

    class LoginForm extends React.Component {
        render() {   
            return (
                <div className="login-form-root">
                    {this.state.displayLoading && <Loading loadingFrom={this.displayName}/>}
                </div>
            );
        }
    }
    

    UPDATE (after multiple comments saying its not working)

    As per convention, react offers a code snippet to wrap getting the component name on their documentation which is the following:

    function withSubscription(WrappedComponent) {
      class WithSubscription extends React.Component {/* ... */}
      WithSubscription.displayName = `WithSubscription(${getDisplayName(WrappedComponent)})`;
      return WithSubscription;
    }
    
    function getDisplayName(WrappedComponent) {
      return WrappedComponent.displayName || WrappedComponent.name || 'Component';
    }
    

    As can be seen, they first check the display name, then the component name, and if all fails, then it will be just 'Component'

    0 讨论(0)
  • 2020-12-05 18:56

    You can use this.constructor.name to obtain the name of your component.

    (Using React 16.x as of this writing)

    Caveat: This won't work if you're minifying for production with Webpack.

    0 讨论(0)
提交回复
热议问题