如何从父组件内部选择性地管理子组件的道具?

问题描述 投票:0回答:1

请考虑以下组件:

1)

import React from 'react';

const toolbar = (props) => (
  <header>   
    <nav>
        <ul>
            <li style={{display: props.displayHome}}>Home</li>
            <li>About Us</li>
            <li>Contact</li>
        </ul>
    </nav>   
  </header>
);

export default toolbar;

2)

import React, {Component} from 'react';

import Toolbar from '../../components/Navigation/Toolbar/Toolbar';

class Layout extends Component {
  render() {   
    return (
      <div>
        <Toolbar displayHome={this.props.displayHome}/>
        <main>
          {this.props.children}
        </main>
      </div>
    );
  }
}

export default Layout;

3)

import React, { Component } from 'react';
import {Route, Switch} from 'react-router-dom';

import Layout from './hoc/Layout/Layout';
import Homepage from './components/Homepage/Homepage';
import CategoryPage from './containers/CategoryPage/CategoryPage';
import SingleMealPage from './containers/SingleMealPage/SingleMealPage';
import SearchPage from './containers/SearchPage/SearchPage';
import AboutUsPage from './components/AboutUs/AboutUsPage';
import ContactPage from './components/Contact/ContactPage';

class App extends Component {
  render() {
    return (
      <div>
        <Layout>
          <Switch>
            <Route path="/category" component={CategoryPage} />
            <Route path="/singleMeal" component={SingleMealPage} />
            <Route path="/searchResults" component={SearchPage} />
            <Route path="/aboutUs" component={AboutUsPage} />
            <Route path='/contact' component={ContactPage} />
            <Route path="/" component={Homepage} />
          </Switch>
        </Layout>
      </div>
    );
  }
}

export default App;

我想在除主页上的所有页面上显示“主页”选项卡。

我显然可以通过在每个相关组件中导入工具栏组件,然后分别管理“ displayHome”属性来做到这一点,但是有没有办法在当前设置下实现此目的?

reactjs routes switch-statement
1个回答
0
投票
在您的情况下,最简单的方法是检查App组件中的(this.props.location.pathname === '/')并将结果传递给Layout
© www.soinside.com 2019 - 2024. All rights reserved.