admin管理员组

文章数量:1182736

I'm trying to create a higher order component but keep getting this eslint waring.

component definition is missing display name

I tried adding a display name like below but it still complains.

import React from 'react';

const HOC = props => (WC) => {
  WC.displayName = 'test'
  return (
    <WC />
  );
}

export default HOC;

I'm trying to create a higher order component but keep getting this eslint waring.

component definition is missing display name

I tried adding a display name like below but it still complains.

import React from 'react';

const HOC = props => (WC) => {
  WC.displayName = 'test'
  return (
    <WC />
  );
}

export default HOC;
Share Improve this question edited Feb 9, 2019 at 0:34 Chris 59.5k20 gold badges119 silver badges142 bronze badges asked Feb 9, 2019 at 0:30 me-meme-me 5,80914 gold badges61 silver badges111 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 26

Two things you need to correct.

First: Fix order of your functional component declaration.

Second: setting displayName to the component returned from HOC

const HOC = WC => {
  const MyComp = (props) => {
    return (
        <WC {...props} />
      );
  }
  MyComp.displayName = 'test'
  return MyComp;
}

Once you make the above change. You just need to use the HOC like

const MyCompWithHoc = HOC(CompA);

and render it like

<MyCompWithHoc propsA={'A'} {...otherPropsYouWantToPass} />

HOC is the component that's lacking a displayName property. The code you have above is changing the displayName property of WC which you don't want.

HOC.displayName = 'some higher component'

Your HOC should take the component as the first argument instead of props, see the example in the React docs: https://reactjs.org/docs/higher-order-components.html#convention-wrap-the-display-name-for-easy-debugging

EDIT: You can pass it props either by returning a functional component:

const HOC = WC => props => {
  WC.displayName = 'test'
  return (
    <WC {...props} />
  );
}

Or just return the wrapped component after setting the displayName:

const HOC = WC => {
  WC.displayName = 'test';
  return WC;
}

本文标签: javascriptcomponent definition is missing display name on HOCStack Overflow