使用React Router当前路由在菜单上有条件地设置活动类

dagda1

我正在使用React Router 1.0.2,我的路由如下所示:

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <Route path="/" component={App}>
        <IndexRoute component={Home}/>
        <Route path="triangles" component={Triangles}/>
      </Route>
    </Router>
  </Provider>,
  document.querySelector('.container')
);

我的App组件如下所示,我认为我可以在道具中传递位置:

import React, {Component} from 'react';

import Menu from './menu';

export default class App extends Component {
  render() {
    return (
      <div>
        <Menu/>
        <div className="jumbotron">
         {this.props.children && React.cloneElement(this.props.children, {
            location: this.props.location
          })}
        </div>
      </div>
    );
  }
};

我想在Menu组件上有条件地设置一个活动类:

import React, {Component} from 'react';

import { pushPath } from 'redux-simple-router';
import { Link } from 'react-router';

    export default class Menu extends Component {
      render() {
        return (
            <nav role="navigation" className="navbar navbar-default">
              <div id="navbarCollapse" className="collapse navbar-collapse">
                <ul className="nav navbar-nav">
                  <li className={this.props.location.pathname === '/' ? 'active' : ''}>
                    <Link to="/">Home</Link>
                  </li>
                </ul>
              </div>
            </nav>
        );
      }
    };

但是,this.props.location当调用菜单的render函数时,n为null吗?

如何将道具传递给子组件?

米歇尔·提里(Michelle Tilley)

好像您没有将prop传递到正确的元素中。childrenApp将是什么子路径被渲染(所以无论是HomeTriangles),但你想要的道具要传递给Menu

为此,只需通过JSX将其传递:

import React, {Component} from 'react';

import Menu from './menu';

export default class App extends Component {
  render() {
    return (
      <div>
        <Menu location={this.props.location} />
        <div className="jumbotron">
          {this.props.children}
        </div>
      </div>
    );
  }
};

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在React中有条件地设置活动类

使用AngularJS在选项标签上有条件地设置类

使用 React Router 有条件地重定向

react-router-dom 有条件地构建路由并将参数传递给基于类的组件

如何在 React 库上有条件地使用 next/image 组件?

在React Native中有条件地设置初始路由

基于路由有条件地渲染 CSS (React)

React-native - 有条件地设置高度

React-Router:如何有条件地将路由重定向到另一个 url?

React有条件地显示链接,如果json文件上有内容?

使用dplyr有条件地设置列名称

使用vueJS有条件地设置href属性

如何有条件地使用React Native元素

使用React有条件地停止游戏循环

我如何使用springdoc openapi在swagger ui上有条件地忽略PathVariable

如何在 WooCommerce 单个产品页面上有条件地使用短代码

有没有一种干净的方法可以有条件地为同一React Router路由加载和渲染不同的组件?

在React中基于路由有条件地渲染组件

如何在React.JS中有条件地添加路由?

使用React的className属性和PostCSS在三元中有条件地添加多个类

有条件地禁用滚动到顶部的dom change react router

有条件地设置 React 中所有 html 标签的样式

使用角度UI路由器有条件地导航到状态

如何使用一个按钮有条件地路由?(扑)

使用dplyr mutate函数根据当前行有条件地创建新变量

React js 有条件地将类渲染到特定的映射项

如何有条件地设置语义UI React Grid列的width属性?

在React.js中有条件地设置html属性

如何在 React 中有条件地设置状态?