我有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>
简单的方法是根据状态呈现链接内容。
在渲染中只渲染一个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>
)
}
}
<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>