组件定义缺少显示名称 react/display-name

IT技术 reactjs eslint
2021-03-24 19:49:19

如何为此添加显示名称?

export default () =>
  <Switch>
    <Route path="/login" exact component={LoginApp}/>
    <Route path="/faq" exact component={FAQ}/>
    <Route component={NotFound} />
  </Switch>;
4个回答

直接导出箭头函数不会给组件一个displayName,但如果导出一个常规函数,函数名称将用作displayName

export default function MyComponent() {
  return (
    <Switch>
      <Route path="/login" exact component={LoginApp}/>
      <Route path="/faq" exact component={FAQ}/>
      <Route component={NotFound} />
    </Switch>
  );
}

您也可以将函数放入一个变量中,displayName手动在函数上设置,然后将其导出。

const MyComponent = () => (
  <Switch>
    <Route path="/login" exact component={LoginApp}/>
    <Route path="/faq" exact component={FAQ}/>
    <Route component={NotFound} />
  </Switch>
);

MyComponent.displayName = 'MyComponent';

export default MyComponent;
我尝试了解决方案,但仍然出现组件定义缺少显示名称错误。这是我收到错误的地方: export default withAuthenticationRequired(DownloadCodeSamplesPage, { onRedirecting: () => <LoadingSpinner /> }); 在加载微调器上。这是我的组件导出默认函数 LoadingSpinner() { return ( <div className="loading"> <SprkBox className="data-product-loader sprk-u-AbsoluteCenter"> <SprkIcon additionalClasses="loading sprk-c-Icon- -xxl" iconName="update" /> </SprkBox> </div> ); }
2021-05-24 19:49:19
好吧,那么另一个问题......我为什么要关心displayName
2021-05-25 19:49:19
@CorayThan 它主要由开发人员工具用来为您使用的组件命名。如果组件没有displayNameis 将显示为<Unknown />
2021-06-03 19:49:19
或者,如果您想按类型过滤组件。
2021-06-04 19:49:19

tldr:将箭头函数切换为命名函数

显示的 Lint 错误:Component definition is missing display name react/display-name

要解决,您可以命名您的函数(IOW,不要使用箭头函数)。在此示例中,我使用react-table并传递了一个自定义组件以在单元格中呈现。

没有错误:

{
  Cell: function OrderItems({ row }) {
    return (
      <a>
        View Items
      </a>
    );
  },
}

错误:

{
  Cell: ({ row }) => (
    <a>
      View Items
    </a>
  )
}

一种在displayName不创建命名函数的情况下向匿名组件函数添加属性的方法是使用recompose

import { compose, setDisplayName } from 'recompose';

export default compose(setDisplayName('SomeComponent'))(props => ...);

要不就:

export default Object.assign(props => ..., { displayName: 'SomeComponent' });

同样,如果您有一个功能组件,例如:

export default function test(){
    

return (<div></div>

}

并在其中创建另一个组件,例如文本框,该文本框通过使用 refs 更新功能组件内部的状态,以确保整个页面不会重新呈现,并且只需要为该组件指定一个显示名称。否则会出现构建错误。

export default function test(){
    const stateForFunctionalComponent = useRef("");

    const seperateTextBoxState = React.forwardRef((props,ref) => {
    const [textBoxDocTitle, setTextBoxDocTitle] = useState("");
    
    useEffect(() => {
      ref.current = textBoxDocTitle;
    },[textBoxDocTitle])
  
    return <input 
      id="somethingUnique" 
      type="text" 
      required="required" 
      placeholder="Enter document name..." 
      onInput={(e) => setTextBoxDocTitle(e.target.value)}>
  </input>})

    //Line that matters!!!
    seperateTextBoxState.displayName = "seperateTextBoxState";
}

    return (<div><seperateTextBoxState ref={stateForFunctionalComponent}/></div>)
}