簡體   English   中英

React - 通過功能組件傳遞 props up 組件樹

[英]React - passing props up components tree through functional components

我想在我的組件樹中將一個簡單的字符串、數字或 boolean 向上傳遞一個以上的級別。 根據我讀到的內容,我需要使用回調函數來執行此操作,但我似乎無法正確理解邏輯。

這是我將道具從父應用程序傳遞給孫子面包屑的示例。 我希望這個道具實際上來自樹中的最后一個孩子,即“ResultsPage”組件。

我意識到有更好的方法來做這樣的事情(redux、上下文、不同的結構等),對我來說,這里的重點是學習和理解如何使用回調函數以及如何傳遞一個多於 1 個級別的支撐。

新手友好請-感謝您的任何意見:)

class App extends React.Component {
  render() {
    return (
      <>
        <h1>Top level app</h1>

        {/* I import the header and pass down prop */}
        <Header currentLocation="Results Page" />

        {/* I import the main app content */}
        <ResultsPage />
      </>
    );
  }
}

function Header(props) {
  return (
    <>
      <h2>
        This is the header element. It will have some nav items and the
        breadcrumb I import
      </h2>

      {/* I import the breadcrumb accept the props from parent and pass the props down to child */}
      <Crumbs currentLocation={props.currentLocation} />
    </>
  );
}

function Crumbs(props) {
  return (
    <>
      {/* I display the props I passed down through the tree */}
      <h3>
        <small>This is the breadcrumb, you are on</small>{" "}
        {props.currentLocation}
      </h3>
    </>
  );
}

function ResultsPage() {
  return (
    <>
      <p>
        This is the actual results content. I would like this component to tell
        the header component that I have loaded so it can update the breadcrumb
        to let it know which page is currently loaded in the app.
      </p>
    </>
  );
}

export default App;

為了完成這個問題,我放棄了以下解決方案:

Codesandbox:初始問題的解決方案

Codesandbox:僅使用功能組件來解決相同問題的附加解決方案

希望它可以幫助下一個人:)

維護一個本地的 state 變量來存儲位置,並通過 props 傳遞一個回調 function 來設置它。

class App extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      currentLocation : "InitialLocation"
    }
  }

  changeCurrentLocation = (newLocation) => {
    this.setState({currentLocation : newLocation})
  }

  render() {
    ...
    <ResultsPage callback={this.changeCurrentLocation}/>
  }
}

changeCurrentLocation function 將新位置作為參數並修改 state。 每次 state 更改時,都會再次調用渲染 function。 這將使用更新的 state 信息(在您的情況下為 currentLocation)刷新視圖。

function ResultsPage({ callback }) {
  useEffect(() => {
    callback('My Results');
  }, [callback])

  return (
    ...
  );
}

最好的方法是這樣做,因為我認為將 state 保存在 redux 商店中。 您可以使用 redux 中的subscribe()方法創建一個偵聽器,以偵聽來自父組件的子組件的任何調度。

還有一些簡單的方法,你可以使用本地存儲。 您可以使用window.addEventListener('storage', function(e) { }回調方法從子組件存儲值並由父組件偵聽。希望您能理解我想說的話。

暫無
暫無

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

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