簡體   English   中英

ReactJS 如何將道具傳遞給 state 中的組件

[英]ReactJS How to pass a prop to a component in state

function App() {
   const [currentPanel, setCurrentPanel] = useState(ProfilePanel); // ProfilePanel is a component
     return (
          <div className={styles.App}>
                    {currentPanel}     
          </div>
     );
}

在代碼中,我將組件“ProfilePanel”設置為“curentPanelel”state,然后在 App 中更改 state 中的組件,這會呈現另一個面板。 問題是當我這樣渲染它時我不知道如何傳遞道具。 我嘗試了{currentPanel()}但返回錯誤。 請幫助找到解決此問題的方法,或者如果此方法在 state 中渲染組件是絕對錯誤的,請告訴如何以另一種方式執行此操作。

問題是當我像這樣渲染它時我不知道如何傳遞道具

您可以使用 state 成員的首字母大寫字母( CurrentPanel而不是currentPanel ),然后正常使用它( <CurrentPanel someProp="some value" /> )。 (它必須是最初的上限,因為 JSX 就是這樣知道它應該是一個組件,而不是標簽名稱。)但是,你將很難在 state 中設置一個不同的組件 function,因為組件函數就是函數, and when you pass a function to a state setter, it thinks you're using the callback version of the state setter and calls your function, rather than setting it in state.

如果您絕對必須在 state 中保存組件 function,請將其包裹在 object 中,但您更有可能嘗試解決整體問題。

暫無
暫無

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

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