反应:链接未激活时显示第1个孩子/隐藏第2个孩子,链接激活时隐藏第1个孩子/显示第2个孩子?

时间:2016-08-10 18:11:40

标签: reactjs react-router react-redux

我有2个链接,每个2个孩子,当父链接未激活时,都需要显示他们的第一个孩子/隐藏他们的第二个孩子,然后当父链接处于活动状态时隐藏第一个孩子/显示第二个孩子。我怎么能在React中完成这个?

<Link activeClassName="active" className="sidebar-link" to="/tech/link1">
    <span className="collapsed">
        Title
    </span>
    <div className="expanded">
        Content
    </div>
</Link>

<Link activeClassName="active" className="sidebar-link" to="/tech/link2">
    <span className="collapsed">
        Title
    </span>
    <div className="expanded">
        Content
    </div>
</Link>

1 个答案:

答案 0 :(得分:0)

简单的方法是根据状态呈现链接内容。

在渲染中只渲染if like

  {/* only rendered if activeMenuId === 2 */}
   {
     activeMenuId === 2 &&
     <span className="collapsed">
       Title
     </span>
   } 
   {/* only rendered if activeMenuId === 1 */}
   {
     activeMenuId === 1 &&
     <div className="expanded">
       Content
     </div>
   } 

更多代码来说明我的意思:

&#13;
&#13;
import React, { Component } from 'react';
import { Link } from 'react-router';

class demo extends Component {
 constructor(props) {
   super(props);
   this.state = {
     activeMenuId: 1 // assuming at least 1 menu active
   };
 }
  
 render() {
  const { activeMenuId } = this.state; // destructuring helps for readability see below
   
  return (
    <div>
      {/* first menu */}
      <Link 
        activeClassName={activeMenuId === 1 ? 'active' : ''}
        className="sidebar-link" 
        to="/tech/link1">
    
        {/* only visible if menuId = 1 is active */}
        {
          activeMenuId === 1 &&
          <span className="collapsed">
            Title
          </span>    
        }
    
        {/* only visible if menuId= 2 is active */}
        {
          activeMenuId === 2 &&
          <div className="expanded">
            Content
          </div>
        }    
      </Link>

     {/* second menu */}
     <Link 
       activeClassName={activeMenuId === 2 ? 'active' : ''}   
       className="sidebar-link" 
       to="/tech/link2">
       {/* only visible if menuId = 1 is active */}
       {
         activeMenuId === 2 &&
         <span className="collapsed">
           Title
         </span>
       } 
       {/* only visible if menuId= 1 is active */}
       {
         activeMenuId === 1 &&
         <div className="expanded">
           Content
         </div>
       }        
      </Link>
    </div>
  )
 }
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
&#13;
&#13;
&#13;