error Missing “key“ prop for element in array react/jsx-key

文章讲述了开发者在React项目中遇到的一个关于jsx中map函数使用key属性的错误,尽管已经在其他地方正确设置了key,但在Modal的footer部分的第一个元素上仍然报错。作者发现这是因为在数组的第一个元素上需要特别添加key,通过单元测试验证了这一问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

react遇到一个奇怪的问题 

error Missing "key" prop for element in array react/jsx-key

检查了jsx中使用map的,都定义了key

<div className="docTypeListBox">
              {otherList.map((item: any) => {
                return (
                  <DocItem
                    key={item.document_id}
                    item={item}
                    showDemo={showDemo}
                    tabName={tabName}
                    type="otherDoc"
                    showTopClick={showTopClick}
                  />
                );
              })}
            </div>

但还是报错,代码提交eslint一直提示

最终,通过单元代码测试,发现是这货

<Modal
          centered
          className="demoModal"
          title={currentDemo.example_title}
          open={isDemoOpen}
          onCancel={demoModalCancel}
          width={650}
          footer={[
            <div className="flex-acen-sb">
              <div className="flex-aitem-center">
                <div className="rate-circle f-s-14"></div>
                <div className="m-l-10">NO.{docNo}</div>
              </div>
              <div>
                <Tooltip
                  placement="top"
                  title={documentType === 'otherDoc' ? '置顶外展示' : '外展示'}
                  arrow={true}
                  className={`card-more ${documentType === 'otherDoc' ? 'cursor-point' : ''}`}
                >
                  {documentType === 'otherDoc' ? (
                    <div onClick={() => showTopClick(currentArticle)}>
                      <img src={topdisplay} height={15} width={15} />
                    </div>
                  ) : (
                    <div>
                      <img src={outdisplay} height={15} width={15} />
                    </div>
                  )}
                </Tooltip>
              </div>
            </div>,
          ]}
        >

因为使用了数组,数组的第一个元素要用key

// 注意看key="meishayong"
<Modal
          centered
          className="demoModal"
          title={currentDemo.example_title}
          open={isDemoOpen}
          onCancel={demoModalCancel}
          width={650}
          footer={[
            <div className="flex-acen-sb" key="meishayong">
              <div className="flex-aitem-center">
                <div className="rate-circle f-s-14"></div>
                <div className="m-l-10">NO.{docNo}</div>
              </div>
              <div>
                <Tooltip
                  placement="top"
                  title={documentType === 'otherDoc' ? '置顶外展示' : '外展示'}
                  arrow={true}
                  className={`card-more ${documentType === 'otherDoc' ? 'cursor-point' : ''}`}
                >
                  {documentType === 'otherDoc' ? (
                    <div onClick={() => showTopClick(currentArticle)}>
                      <img src={topdisplay} height={15} width={15} />
                    </div>
                  ) : (
                    <div>
                      <img src={outdisplay} height={15} width={15} />
                    </div>
                  )}
                </Tooltip>
              </div>
            </div>,
          ]}
        >

### 解决方案 当遇到 `Component definition is missing display name` 的 ESLint 错误时,这通常是因为定义的函数组件或高阶组件 (HOC) 缺少显式的 displayName 属性。displayName 是用于调试工具中的名称标识符,虽然它不是运行时必需的部分,但在开发过程中可以帮助更清晰地区分不同的组件。 以下是修复此问题的方法: #### 方法一:为匿名函数组件设置 displayName 如果使用箭头函数创建了一个无状态函数组件,则可以通过手动为其分配一个 displayName 来解决问题。例如: ```javascript import React from 'react'; const MyComponent = () => { return <div>Hello World</div>; }; MyComponent.displayName = 'MyComponent'; // 显式声明 displayName [^3] export default MyComponent; ``` 通过这种方式可以满足 ESLint 对于 `react/display-name` 的要求。 #### 方法二:直接命名函数组件而非使用匿名形式 另一种方法是避免使用匿名函数作为组件定义的方式,而是采用具名函数的形式来定义组件。这样就不需要额外指定 displayName,因为函数的名字会自动成为该组件的 displayName。如下所示: ```javascript function AnotherComponent() { return ( <h1>Another Component!</h1> ); } export default AnotherComponent; // 函数名即为组件名 [^4] ``` #### 方法三:处理 HOC 中缺失的 displayName 对于高阶组件(Higher Order Components),也需要确保它们传递原始组件的 displayName 或者自己提供一个新的 displayName。下面是一个例子展示如何保留原有组件的名字或者给新的 HOC 设置名字: ```javascript import React from 'react'; import PropTypes from 'prop-types'; function withSubscription(WrappedComponent) { class WithSubscription extends React.Component { render() { /* ... */ return <WrappedComponent {...this.props} />; } } WithSubscription.displayName = `WithSubscription(${getDisplayName(WrappedComponent)})`; [^5] return WithSubscription; } function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; } ``` 以上代码片段展示了如何在一个简单的 HOC 上应用 displayName 的最佳实践。 ### 总结 为了消除 `Component definition is missing display name` 这类错误提示,开发者可以选择多种方式来保证每一个自定义组件都有其对应的 displayName 值设定好。无论是简单地添加静态属性还是利用工厂模式生成带特定前缀的新显示标签都是可行之策。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值