简体   繁体   English

将 App.js 的状态传递给子组件

[英]Passing State of App.js to Child Component

I'm working on the main page of a website and I'd like to have a specific nav/menu bar for the main page and a different one for the other components (the main page hides de "home" button and the others show it).我正在网站的主页上工作,我想为主页设置一个特定的导航/菜单栏,为其他组件设置一个不同的导航栏(主页隐藏“主页”按钮,其他显示它)。

The issue I have at the moment is that the logic of rendering this menu lives on App and I'm having a hard time to find the proper way to pass the state of my App component to the other components, probably just because of the lack of experience.我目前的问题是,呈现这个菜单的逻辑存在于 App 上,我很难找到将我的 App 组件的状态传递给其他组件的正确方法,可能只是因为缺少的经验。

import React from "react";
import { BrowserRouter, Route, Link } from "react-router-dom";
import Main from "./main";
import MapContainer from "./mapcontainer";
import Venue from "./venue";
import Schedule from "./schedule";
import Accommodation from "./accommodation";
import Couple from "./couple";
import Honeymoon from "./honeymoon";
import Uploader from "./uploader";
import Friday from "./friday";
import Saturday from "./saturday"
import Sunday from "./sunday";
import Dresscode from "./dresscode";

export class App extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            error: false,
            isHome: true
        };        
    }

    componentDidMount() {
        console.log("App mounted");
    }


    render() {

        function HomeComponentMenu(props) {
            return (
                <nav className="header-on-app">
                    <button>Contact Us</button>
                    <button className="logout-btn"><a href="/logout">Logout</a></button>
                </nav>
            );
        }

        function AllOtherComponentsMenu(props) {
            return (
                <nav className="header-on-app">
                    <button><Link to="/">Home</Link></button>
                    <button>Contact Us</button>
                    <button className="logout-btn"><a href="/logout">Logout</a></button>
                </nav>
            );
        }

        const isHome = this.state.isHome;
        let menu;

        if (isHome) {
            menu = <HomeComponentMenu/>;
        } else {
            menu = <AllOtherComponentsMenu/>;
        }

        return (
            <BrowserRouter>

              <nav className="header-on-app">{menu}</nav>
                <div className="app-container">     
                    <Route exact path="/" component={Main} />
                    <Route exact path="/venue" component={Venue}/>
                    <Route exact path="/venuemap" component={MapContainer}/>
                    <Route exact path="/schedule" component={Schedule}/>
                    <Route exact path="/accommodation" component={Accommodation}/>
                    <Route exact path="/couple" component={Couple}/>
                    <Route exact path="/honeymoon" component={Honeymoon}/>
                    <Route exact path="/uploader" component={Uploader} />
                    <Route exact path="/friday" component={Friday} />
                    <Route exact path="/saturday" component={Saturday} />
                    <Route exact path="/sunday" component={Sunday} />
                    <Route exact path="/dresscode" component={Dresscode} />
                </div>
            </BrowserRouter>
        );
    }
}

Component I'd like to set isHome to false我想将 isHome 设置为 false 的组件

import MapContainer from "./mapcontainer";


export default class Venue extends React.Component {
    constructor(props){
        super(props);

        this.state = {
            error:false,
        }
    }
    render() {
        return (
            <div className="venue-container">

            <h1>Anna & Rodolfo</h1>
            <h2><span>_______</span> Venue . Local . Veranstalungsort <span>_______</span></h2>
            {this.state.error && <h2 className="error">Ops! Something went wrong.</h2>}

            <div className="grid-container-venue">


                    <div className="item">
                    <img src="venue.png" alt="Avatar" className="image"/> 
                    <div className="background-grid-items">
                    <div className="text-address">
                    <a href="https://www.g71972,15z/data=!4887b!8m2!3d52.47094!4d12.71972">
                        <p>Kulturschloss</p>
                        <p>Abcd.30 3456 Berlin </p>
                        <p>Germany . Alemanha . Deutschland</p>
                    </a>    
                    </div>
                    </div>
                    </div>

                    <div className="item">
                    <img src="website.png" alt="Avatar" className="image"/> 
                    <div className="background-grid-items">
                    <div className="text">
                    <a href="https://www.kult.de/">   
                        <p>To the Website</p>
                        <p>Para o Website</p>
                        <p>Zur Website</p>
                    </a>    
                    </div>
                    </div>
                    </div>

                    <div className="item">
                    <img src="transportation.png" alt="Avatar" className="image"/>    
                    <div className="background-grid-items">
                    <div className="text">
                        <p>Transportation</p>
                        <p>Traslado</p>
                        <p>Transport</p>
                    </div>
                    </div>
                    </div>

                    <div className="item">
                        <div className="background-grid-venue">
                            <div className="map">
                            <MapContainer/>
                            </div>
                        </div>
                    </div>

            </div>
        </div>

        );
    }
}

Since my components are being rendered by React Router, I tried to render props passing it in an inline function and afterwards pass along to the argument I was creating, but somehow it didn't work.由于我的组件是由 React Router 渲染的,我尝试渲染 props 将它传递到一个内联函数中,然后传递给我正在创建的参数,但不知何故它不起作用。 Would you have any suggestions on how to solve this?你对如何解决这个问题有什么建议吗? Thank you very much!非常感谢!

To pass a state to a child component, you have to pass it as props of the child component.要将状态传递给子组件,您必须将其作为子组件的 props 传递。

eg例如

import React, { Component } from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import TableView from './TableView'

export default class App extends Component {
  state = {
    item: 'this is the item'
  }

render() {
  return(
    <Router>
      <Route exact path="/home">
        <TableView itemList={this.state.item}></TableView>
      </Route>
    </Router>
  )
}

}

to get the props in the child component获取子组件中的道具

import React, { Component } from 'react'

export default class TableView extends Component {
  render(){
    <React.Fragment>
      {this.props.item}
    </React.Fragment>
  }
}

Hope it helps希望能帮助到你

EDIT: It would also help to debug if you have the react devtools addons in your browser to check if the values of the state of each component编辑:如果您的浏览器中有 react devtools 插件来检查每个组件的状态值,这也有助于调试

To pass props to a react route you have to define it in the render function like this:要将道具传递给反应路线,您必须在渲染函数中定义它,如下所示:

<Route exact path="/venue" render={(props) => <Venue updateHomeState={this.updateHomeState}/>}/>

To alter the isHome state on the parent, you could define that function on the parent like:要更改父级上的 isHome 状态,您可以在父级上定义该函数,例如:

updateHomeState = (newState) => { 
    this.setState({ isHome: newState }) 
} 

And then call it in componentDidMount() of your child component like this.props.updateHomeState(newState) .然后在子组件的componentDidMount()中调用它,如this.props.updateHomeState(newState)

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

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