【问题标题】:Passing State of App.js to Child Component将 App.js 的状态传递给子组件
【发布时间】:2020-05-18 00:11:46
【问题描述】:

我正在处理网站的主页,我希望主页有一个特定的导航/菜单栏,其他组件有一个不同的导航/菜单栏(主页隐藏了“主页”按钮和其他人显示它)。

我目前遇到的问题是,呈现此菜单的逻辑存在于 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>
        );
    }
}

我想将 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>

        );
    }
}

由于我的组件是由 React Router 渲染的,我尝试渲染 props 并通过内联函数传递它,然后传递给我正在创建的参数,但不知何故它不起作用。你对如何解决这个问题有什么建议吗?非常感谢!

【问题讨论】:

    标签: javascript reactjs react-router state react-props


    【解决方案1】:

    要将道具传递给反应路线,您必须在渲染函数中定义它,如下所示:

    &lt;Route exact path="/venue" render={(props) =&gt; &lt;Venue updateHomeState={this.updateHomeState}/&gt;}/&gt;

    要更改父级的 isHome 状态,您可以在父级上定义该函数,例如:

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

    然后在您的子组件的componentDidMount() 中调用它,例如this.props.updateHomeState(newState)

    【讨论】:

    • 非常感谢!一开始效果很好。主页有我想要的导航栏,当我进入场地页面时,我可以看到包含“主页”按钮的新导航栏。唯一的问题是,当我单击按钮并被重定向回主页时,导航栏会更新,并且“主页”按钮又会回到那里。我现在要去看看并尝试改变行为,但非常感谢!
    • 不客气 :) 我更新了我的答案,展示了如何将相同的函数传递给不同的组件,并让它们以不同的方式影响 isHome 状态。您可以以相同的方式将其传递给main 组件,并使用true 而不是false 调用它,就像在子组件中一样。
    • 再次感谢您,@Lazarus!我很确定您的解决方案会很有帮助!
    【解决方案2】:

    要将状态传递给子组件,您必须将其作为子组件的 props 传递。

    例如

    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>
      )
    }
    
    }
    

    获取子组件中的道具

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

    希望对你有帮助

    编辑: 如果您在浏览器中有 react devtools 插件来检查每个组件的状态值是否也有助于调试

    【讨论】:

      猜你喜欢
      • 2019-09-29
      • 2019-01-20
      • 2022-01-18
      • 2019-04-02
      • 2019-02-17
      • 1970-01-01
      • 2021-11-12
      • 2022-07-15
      • 2019-08-15
      相关资源
      最近更新 更多