简体   繁体   English

React.Js 将道具从组件传递到 NavBar 组件?

[英]React.Js Passing props from component to NavBar component?

So I have React.JS page and this page is made out of two parts.所以我有 React.JS 页面,这个页面由两部分组成。 The NavBar and the page content. NavBar 和页面内容。

In the App.js I am passing props to the page and I want to display this props in the NavBar as Page title.在 App.js 中,我将道具传递给页面,我想在 NavBar 中显示此道具作为页面标题。 How can I do this?, basicaly every link has it own props, which is the name of the page and I wouls like to display this props in the PageHeader component.我该怎么做?基本上每个链接都有自己的道具,这是页面的名称,我想在 PageHeader 组件中显示这个道具。

import {BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Banany from "./Banany";
import Broskve from "./Broskve";
import PageHeader from "./Components/PageHeader";
import Home from "./Home";
import Hrusky from "./Hrusky";


function App() {
  return (
    <Router>
      <PageHeader/>

      <Switch>
        <Route exact path="/">
          <Home pageTitle="Home"/>
        </Route>
        <Route path="/banany">
          <Banany pageTitle="Bananas"/> <--- I want to display Bananas in PageHeader component
        </Route>
        <Route path="/broskve">
          <Broskve pageTitle="Broskve"/>
        </Route>
        <Route path="/hrusky">
          <Hrusky pageTitle="Pears"/>
        </Route>
      </Switch>

    </Router>
  );
}

export default App;

There are all kinds of methods of doing this.有各种各样的方法可以做到这一点。
2 most relevant that come to mind:想到的 2 个最相关的:

  • Give every route a param, ie pageTitle , just like you pass to every comp.给每条路线一个参数,即pageTitle ,就像你传递给每一个 comp 一样。
    Then you can access it from the navbar.然后您可以从导航栏访问它。
  • Manage a global state, either with a specialized library (redux/etc..), or simply with React's built-in contextAPI.管理全局 state,可以使用专门的库(redux/etc..),也可以简单地使用 React 的内置 contextAPI。

In this case, I would go with the first method as it is simpler if that's all you need.在这种情况下,我会使用第一种方法 go,因为如果这就是您所需要的,它会更简单。

If the Page Header depends on your route just move it inside your Route like so:如果页面 Header 取决于您的路线,只需将其移动到您的路线内,如下所示:

<Route path="/banany">
  <PageHeader pageTitle="Bananas" />
  <Banany pageTitle="Bananas" />
</Route>

Obviously there are other ways to achieve this behavior and it might be repetitiv but this is the straight forward approach.显然还有其他方法可以实现这种行为,它可能是重复的,但这是直接的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM