在 React 中获取组件名称 [英] Get component name in React

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

问题描述

我正在开发一个 React 应用程序.我有一个 Loading 组件,这是一个等待的小动画.我想根据调用它的组件在这个加载组件中添加一条消息.

这是我如何调用我的加载组件(this.state.displayLoading 为 true 或 false):

class LoginForm 扩展 React.Component {使成为() {返回 (<div className="login-form-root">{this.state.displayLoading &&<正在加载loadingFrom={?}/>}

);}}

我想在我的变量 loadingFrom 中获得LoginForm",它是 className.也许这不是正确的做法.

解决方案

您不需要它是动态的,因为您是自己编写组件并且可以将其作为字符串传递

class LoginForm 扩展 React.Component {使成为() {返回 (<div className="login-form-root">{this.state.displayLoading &&<正在加载loadingFrom="登录表单"/>}

);}}

但是,如果您仍然需要访问组件的名称,则可以在组件上定义 displayName 属性

class LoginForm 扩展 React.Component {静态显示名称 = '登录表单';使成为() {返回 (<div className="login-form-root">{this.state.displayLoading &&<正在加载loadingFrom="登录表单"/>}

);}}

并像Component.displayName一样访问它.

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 component which called it.

Here is how i call my Loading component (with this.state.displayLoading at true or false) :

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

I want to get "LoginForm" in my variable loadingFrom, which is the className. Maybe it's not the right way to do that.

解决方案

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.

这篇关于在 React 中获取组件名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆