在反应链接上添加活动类

时间:2017-01-10 11:21:50

标签: javascript reactjs

我有以下内容:

class Link extends React.Component {
    render () {
        return (
            <li data-id={this.props.el}>{this.props.el}</li>
        );
    }
}

class Nav extends React.Component {
    render () {
        var links = ['name', 'color', 'design', 'share'],
            newLinks = [],
            that = this;
        links.forEach(function(el){
            newLinks.push(<Link activeClass={that.props.active} key={el} el={el} />);
        });
        return (
            <ul>
                {newLinks}
            </ul>
        );
    }
}

this.props.active的值可能是&#34; &#39; name&#39;,&#39; color&#39;,&#39; design&#39;,&#39; share&#39; &#34;与数组相同。

基于该值,我想为具有相同data-id = {this.props.el}值的匹配li分配一个活动类..

2 个答案:

答案 0 :(得分:1)

class Link extends React.Component {
    render () {
       var liClass = this.props.isActive ? 'active' : '';
        return (
            <li className={liClass} data-id={this.props.el}>{this.props.el}</li>
        );
    }
}

class Nav extends React.Component {
    render () {
        var links = ['name', 'color', 'design', 'share'],
            newLinks = [],
            that = this;
        links.forEach(function(el){
            newLinks.push(<Link isActive={el === that.props.active} key={el} el={el} />);
        });
        return (
            <ul>
                {newLinks}
            </ul>
        );
    }
}

答案 1 :(得分:1)

我认为这是你想要实现的目标:

class Link extends React.Component {
   render () {
       return (
          <li className={this.props.activeClass} data-id={this.props.el}>{this.props.el}</li>
       );
   }
}

class Nav extends React.Component {
    render () {
        var links = ['name', 'color', 'design', 'share'],
        newLinks = [],
        that = this;
        links.forEach((el, i)=>{
            newLinks.push(<Link activeClass={that.props.active == el ? 'active': ''} key={i} el={el} />);
        });
        return (
           <ul>
               {newLinks}
           </ul>
       );
    }
}