source

React에서 컴포넌트 이름 가져오기

nicesource 2023. 3. 5. 09:55
반응형

React에서 컴포넌트 이름 가져오기

React 어플리케이션을 개발 중입니다.Loading 컴포넌트는 대기용 애니메이션입니다.호출한 컴포넌트에 따라 이 Loading 컴포넌트에 메시지를 추가합니다.

다음으로 Loading 컴포넌트(this.state.display Loading at true 또는 false)를 호출합니다.

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

변수 loadingFrom(className)에서 "LoginForm"을 가져오고 싶습니다.어쩌면 그건 올바른 방법이 아닐지도 몰라.

클래스 컴포넌트

사용할 수 있습니다.this.constructor.name컴포넌트 이름을 가져옵니다.

(이 글에서 React 16.x 사용)

주의: Webpack을 사용한 운용을 최소화하고 있는 경우는, 이 기능은 동작하지 않습니다.

기능 컴포넌트

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

모든React.ComponentJSX가 자동으로 설정하는 속성이 있기 때문에 이론적으로 그 속성을 사용할 수 있습니다.

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

갱신하다 (여러 개의 코멘트가 기능하지 않는다고 한 후)

규칙에 따라 react는 문서상의 컴포넌트명을 취득하기 위한 코드 스니펫을 제공합니다.이러한 코드 스니펫은 다음과 같습니다.

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

function getDisplayName(WrappedComponent) {
  return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}

보시는 바와 같이 먼저 표시명을 확인하고 다음으로 컴포넌트명을 확인합니다.모든 것이 실패했을 경우는, 다음의 순서에 따릅니다.'Component'

HOC의 경우:WrappedComponent.name

웹 팩 빌드 후 작동하도록 함수에 속성을 할당할 수 있습니다.

function MyComponent() {
  return (
    <div />
  );
}
MyComponent.componentName = 'MyComponent';

function ParentComponent({ children }) {
  console.log("Children name", children.type.componentName);
}

디버거를 사용하여 검색한 후 새로운 버전에서는this._reactInternalFiber.elementType.name대신this._reactInternalInstance.getName()

컴포넌트를 직접 쓰고 문자열로 전달할 수 있으므로 동적일 필요는 없습니다.

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

그러나 컴포넌트 이름에 액세스해야 하는 경우displayName컴포넌트의 속성

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

접속할 수 있습니다.Component.displayName.

언급URL : https://stackoverflow.com/questions/43800784/get-component-name-in-react

반응형