React.js实现菜单[突出显示活动链接] [英] React.js implement menu [highlight active link]

查看:97
本文介绍了React.js实现菜单[突出显示活动链接]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下React.js代码使用两个名为"about"和"project"的链接来渲染导航栏.在页面加载时,关于"链接处于活动状态,并显示为红色.单击另一个链接时,导航栏的状态将设置为项目",链接"样式将重新设置,并且项目"将显示为红色.

The following React.js code renders a navbar with two links named 'about' and 'project'. On page load the 'about' link is active and colored red. When the other link is clicked the state of the navbar is set to 'project', 'about' link style is set back, and 'project' is colored red.

我通过在两个链接标签上附加点击处理程序来实现此目的,并将active状态设置为event.target.innerHTML的名称.

I achieve this by attaching a click handler to both link tags, and set the state of active to the name of the event.target.innerHTML.

我是新来的反应者,我认为这是解决该问题的一种非常冗长的方法.我知道有一个activeClassName属性可以传递给react-router链接,但是我想要一种不使用它的方法.

I'm new to react, and I feel this is a really verbose way of going about this. I am aware that there is an activeClassName prop you can pass to a react-router link, but I want a way that does not use it.

import React, { Component } from 'react'
import { Link, Route } from 'react-router'

export default class Navbar extends Component {
    constructor() {
        super();
        this.state = {
            active: 'about'
        }
        this._handleClick = this._handleClick.bind(this);
    }

    _handleClick(e) {
         this.setState({
            active: e.target.innerHTML
         });
    }

    render() {
        let aboutStyle;
        let projectStyle;

        if (this.state.active === 'about') {
            aboutStyle = { color: '#ff3333' };
            projectStyle = {};
        } else {
            aboutStyle = {};
            projectStyle = { color: '#ff3333' };
        }

        return (
        <div className='navbar'> 
            <Link to='/'><h2>BK &#47;&#47;</h2></Link>
            <div className='menu'>
                <Link style={aboutStyle} onClick={this._handleClick} to='about'>about</Link>
                <Link style={projectStyle} onClick={this._handleClick} to='projects'>projects</Link>
            </div>
        </div>
        )
    }
}

推荐答案

在伪代码中可能略微冗长...

maybe slightly less verbose... in Pseudocode

const menuItems = [
   'projects',
   'about',
];

class MenuExample extends React.Component {

  _handleClick(menuItem) { 
    this.setState({ active: menuItem });
  }

  render () { 
    const activeStyle = { color: '#ff3333' };

    return (
       <div className='menu'>  
         {menuItems.map(menuItem => 
            <Link 
             style={this.state.active === menuItem ? activeStyle : {}} 
             onClick={this._handleClick.bind(this, menuItem)}
            > 
              {menuItem}
            </Link>
         )}
       </div>
    );    
  }
}

这篇关于React.js实现菜单[突出显示活动链接]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆