简体   繁体   中英

React HOC returns an anonymous _class

I'm using MaterialUI, more specifically the TextField component which I want to decorate somehow to handle validation state at a component level.

I know about the HOC in react, which is a pattern that seems to be perfect for this. But I have to return an anonymous class and therefore I cannot get the value of the TextField component as I should, because the type returned is _class instead of TextField .

Am I doing something wrong with the HOC pattern, or perhaps this is not the best way to reuse a component without modifying its prototype. Any help would be greatly appreciated.

The HOC declaration

export default function hocInputValidator( WrappedComponent ){
  return class extends Component{
    constructor(props){
      super(props);
    }

    handleChange(){
      console.log('Handling from HOC');
    }

    render(){
      return <WrappedComponent {...this.props}/>
    }
  }
}

The invocation and exporting of the decorated component

export default hocInputValidator(TextField);

When I try to access the decorated component via refs , the type is _class instead of TextField .

HOCs are used mainly for cross cutting of concerns for an example Login. Many components in your app may require Login functionality, hence you can wrap them with an HOC dynamically. An HOC will merely wrap whatever the component that is passed into it. In your case I figured out few issues in your code. I have fixed them below.

export default function ( WrappedComponent ){
     class HocInputValidator extends Component{
        constructor(props){
          super(props);
        }

        handleChange(){
          console.log('Handling from HOC');
        }

        render(){
          return <WrappedComponent {...this.props}/>
        }
      }
      return HocInputValidator;

}

The invocation should be something like this.

import inputValidator from './components/input_validator';

inputvalidator(TextField);

Your HOC returns an anonymous class which is why it's being displayed as _class .

To work around this you can set the HOC's displayName to something descriptive which will override the _class display behaviour.

For instance, you can display the HOC as something like HigherOrderComponent(WrappedComponent) in the DOM which is more descriptive (and easier to debug). It's a convention followed by other libraries such as react-redux .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM