我可以在React片段中添加关键道具吗? [英] Can I add a key prop to a React fragment?

查看:57
本文介绍了我可以在React片段中添加关键道具吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在React中生成一个dl:

I am generating a dl in React:

      <dl>
        {
          highlights.map((highlight, i) => {
            const count = text.split(highlight).length - 1;

            return (
              <>
                <dt key={`dt-${i}`}>{highlight}</dt>
                <dd key={`dd-${i}`}>{count}</dd>
              </>
            );
          })
        }
      </dl>

这给了我警告:

警告:列表中的每个孩子都应该有一个唯一的关键"道具.

Warning: Each child in a list should have a unique "key" prop.

这将删除警告,但不会生成我想要的HTML:

This will remove the warning, but doesn't generate the HTML I want:

      <dl>
        {
          highlights.map((highlight, i) => {
            const count = text.split(highlight).length - 1;

            return (
              <div key={i}>
                <dt>{highlight}</dt>
                <dd>{count}</dd>
              </div>
            );
          })
        }
      </dl>

而且我无法在片段(<> </>)中添加key道具.

And I cannot add a key prop to a fragment (<> </>).

如何解决这个问题?

我正在使用React 16.12.0.

I am using React 16.12.0.

推荐答案

要将键添加到片段,您需要使用完整的Fragment语法:

To add a key to a fragment you need to use full Fragment syntax:

<React.Fragment key={your key}>
...
</React.Fragment>

在此处查看文档 https://reactjs.org/docs/fragments.html#keyed -片段

这篇关于我可以在React片段中添加关键道具吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆