【问题标题】:NextJS - component conditional render occurs problem with duplicated html ID'sNextJS - 组件条件渲染出现重复 html ID 的问题
【发布时间】:2021-08-19 15:20:40
【问题描述】:

我在当前项目中使用 NextJS。其中一个组件支持渲染单行的组件:

const SingleRow = ({ id, label, children }) => {

 return (
  <p id={id}>
   <span>{label}</span>
   <span>{children}</span>
  </p>
 )
}

和下一个在同一个文件中:

...

return (
 <>
  <SingleRow
   id="firstRow"
   label="sample"
  >
   row1
  </SingleRow>

  {hasPhone && <SingleRow
   id="secondRow"
   label="sample"
  >
   row2
  </SingleRow>}

  <SingleRow
   id="thirdRow"
   label="sample"
  >
   row3
  </SingleRow>
 </>
)

hasPhone - 来自 prop 的值,只是一个字符串。

问题: 当第二个 SingleRow 有条件 hasPhone - 它没有正确的 HTML ID(在 chrome 开发工具和赛普拉斯没有看到这个 ID)(应该是 secondRow,是:thirdRow)。当我删除条件时,一切正常,HTML ID 正确。

为什么这种情况会影响 HTML ID?

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    看上面的代码,我只能假设,因为 hasPhone 是一个字符串,它作为一个空字符串传递,所以第二行不会被渲染,只有第一行和第三行。

    const SingleRow = ({ id, label, children }) => {
      return (
        <p id={id}>
          <span>{label}</span>
          <span>{children}</span>
        </p>
      );
    };
    
    export default function App() {
      const hasPhone = "asas"; //make the string empty to omit second row
    
      return (
        <>
          <SingleRow id="firstRow" label="sample">
            row1
          </SingleRow>
    
          {hasPhone && (
            <SingleRow id="secondRow" label="sample">
              row2
            </SingleRow>
          )}
    
          <SingleRow id="thirdRow" label="sample">
            row3
          </SingleRow>
        </>
      );
    }
    

    【讨论】:

    • 你能看到我更新的问题吗?关于您的回答 - 我知道空字符串会隐藏我的组件 :) 问题在于渲染后的 HTML id 重复。
    猜你喜欢
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-21
    相关资源
    最近更新 更多