我有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>
答案 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>
}
更多代码来说明我的意思:
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;