簡體   English   中英

在 React 循環中使用組件函數

[英]Use component function in React loop

聽說 () 的渲染性能不好,所以不應該使用。 但是,在這種情況下,在不帶()的情況下傳遞函數時是無法得到結果的。

您可以在 CodeSendbox 中查看結果: 鏈接

const comp = () => {
  return <div>This is Component</div>;
};

const elements = [comp(), comp];  // Please Attention This Line!
const items = [];

for (const [index, value] of elements.entries()) {
  items.push(
    <div>
      {index}: {value} <br />
    </div>
  );
}

export default function Index() {
  return <>{items}</>;
}

結果是:

0:
This is Component

1: 

為什么只有comp()而不是comp 在這種情況下,最佳做法是什么?

comp是一個返回 JSX 文字的箭頭函數。 它是一個存儲在名為comp的變量中的“函數”。 當作為comp()調用/調用時,注意括號,它被執行並且計算的返回值在數組中返回。 當不帶括號使用時,如comp ,這只是對變量的引用(可以像函數一樣調用)。

函數不是有效的反應孩子,也不是有效的 JSX。

介紹 JSX

const comp = () => {
  return <div>This is Component</div>;
};

const elements = [comp(), comp];  // saves a JSX literal, and a function
const items = [];

for (const [index, value] of elements.entries()) {
  items.push(
    <div>
      {index}: {value} <br /> // trying to render a function here in `value`
    </div>
  );
}

export default function Index() {
  return <>{items}</>;
}

我假設您從一些關於內嵌匿名箭頭函數和事件處理程序以及映射數據數組的文檔中了解到() “不擅長渲染性能”。 那是完全不同的問題。 我相信您的情況只是對如何調用箭頭函數的誤解。

您可以使用 JSX 而不是調用函數:

const comp = () => {
  return <div>This is Component</div>;
};

const elements = [comp, comp];  // Remove the function call, save only the reference
const items = [];

// need to use Value with V instead of v for JSX
for (const [index, Value] of elements.entries()) {
  items.push(
    <div>
      {index}: <Value/> <br /> // render as JSX
    </div>
  );
}

export default function Index() {
  return <>{items}</>;
}

這是一個沙箱鏈接,顯示了它是如何工作的: https : //codesandbox.io/s/cranky-mclean-7ymzr

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM