Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
730 views
in Technique[技术] by (71.8m points)

reactjs - Get component name in React

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Class Components

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.

Functional Components

https://reactjs.org/docs/react-component.html#displayname


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...