0

我在当前项目中使用 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 开发工具和 cypress 中没有看到这个 ID)(应该是 secondRow,是:thirdRow)。当我删除条件时,一切正常,HTML ID 正确。

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

4

1 回答 1

0

看上面的代码,我只能假设,因为 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>
    </>
  );
}
于 2020-10-24T12:49:27.337 回答