簡體   English   中英

在 React 中,我可以在另一個功能組件的主體中定義一個功能組件嗎?

[英]In React, can I define a functional component within the body of another functional component?

我已經開始看到我的一些團隊編寫了以下代碼,這讓我懷疑我們是否以正確的方式做事,因為我以前從未見過這樣寫。

import * as React from "react";
import "./styles.css";

function UsualExample() {
  return <h1>This is the standard example…</h1>
}

export default function App() {
  const CustomComponent = (): JSX.Element => <h1>But can I do this?</h1>
  return (
    <div className="App">
      <UsualExample />
      <CustomComponent />
    </div>
  );
}

它似乎渲染得很好,我看不到任何直接的不利影響,但是我們不應該從另一個組件中定義CustomComponent功能組件是否有一些根本原因?

CodeSandbox 示例: https://codesandbox.io/s/dreamy-mestorf-6lvtd?file=/src/App.tsx:0-342

這不是一個好主意。 每次App重新渲染時,都會對 CustomComponent 進行全新的定義。 它具有相同的功能,但由於它是不同的引用,因此 react 需要卸載舊的並重新安裝新的。 因此,您將強制 react 對每個渲染進行額外的工作,並且您還將重置 CustomComponent 中的任何 state。

相反,組件應該自己聲明,而不是在渲染內部聲明,以便它們只創建一次然后重用。 如有必要,您可以讓組件接受道具來自定義其行為:

const CustomComponent = (): JSX.Element => <h1>But can I do this?</h1>

export default function App() {
  return (
    <div className="App">
      <UsualExample />
      <CustomComponent />
    </div>
  );
}

有時,您可能會在單個組件中重復執行某些操作,並希望通過使用幫助程序 function 來簡化代碼。 沒關系,但是您需要將其稱為 function,而不是將其渲染為組件。

export default function App() {
  const customCode = (): JSX.Element => <h1>But can I do this?</h1>
  return (
    <div className="App">
      {customCode()}
      <UsualExample />
      {customCode()}
    </div>
  );
}

使用這種方法,react 將比較<h1><h1> ,因此不需要重新掛載它。

這不僅是一個壞主意,而且是一個可怕的主意。 你還沒有發現作文(沒關系,這需要一段時間,你會到達那里)。

您想要在另一個組件中聲明組件的唯一原因是關閉您想要在子組件中捕獲的prop (也許還有一些state ) - 這是訣竅 - 將它作為道具傳遞給新的組件,然后您可以在 OUTSIDE 聲明新組件。

轉這個:

function UsualExample() {
  return <h1>This is the standard example…</h1>
}

export default function App({someProp}) {
  // the only reason you're declaring it in here is because this component needs "something" that's available in <App/> - in this case, it's someProp
  const CustomComponent = (): JSX.Element => <h1>I'm rendering {someProp}</h1>
  return (
    <div className="App">
      <UsualExample />
      <CustomComponent />
    </div>
  );
}

進入這個:

function UsualExample() {
  return <h1>This is the standard example…</h1>
}

const CustomComponent = ({someProp}) => <h1>I'm rendering {someProp}></h1>

export default function App({someProp}) {
  return (
    <div className="App">
      <UsualExample />
      { /* but all you have to do is pass it as a prop and now you can declare your custom component outside */ }
      <CustomComponent someProp={someProp} />
    </div>
  );
}

暫無
暫無

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

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