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

如何为其添加显示名称?

export default () =>
<Switch>
<Route path="/login" exact component={LoginApp}/>
<Route path="/faq" exact component={FAQ}/>
<Route component={NotFound} />
</Switch>;
172852 次浏览

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

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

You can also put the function in a variable, set the displayName on the function manually, and then export it.

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;

displayName属性添加到匿名组件函数而不创建命名函数的一种方法是使用 recompose:

import { compose, setDisplayName } from 'recompose';


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

或者只是:

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

Tldr: 将箭头函数切换到命名函数

线条错误显示: Component definition is missing display name react/display-name

To resolve, you can 命名你的函数 (IOW, do not use arrow function). In this example, I am using react-table and passing a custom component to render in a cell.

No error:

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

错误:

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

类似地,如果你有一个功能组件,比如:

export default function test(){
    



return (<div></div>


}

然后在其中创建另一个组件,就像文本框一样,通过使用引用来更新功能组件内部的状态,这样可以确保整个页面不会重新呈现,而仅仅是那个需要给它一个显示名称的组件。否则就会出现构建错误。

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>)
}

如果您正在使用 eslint,这可能是因为没有提供 以下代码 YourclassName . displayName = “ name”

在使用“箭头函数”之前,写下以下代码行对我来说很有用

> /* eslint-disable react/display-name */
Header: () => <strong>ID</strong>,

看看这里是怎么工作的: https://eslint.org/docs/latest/user-guide/configuring/rules