我在React Redux上创建了多级Accordion菜单组件。
class MultiLevelAccordianMenu extends PureComponent {
constructor(props){
super(props);
this.toggleList = this.toggleList.bind(this);
}
toggleList(event){
console.log(event)
}
render(){
return( <ul className="cd-accordion-menu animated">
<li className="has-children" onClick={this.toggleList}>
<input type="checkbox" name ="group-1" id="group-1" defaultChecked />
<label htmlFor="group-1">Group 1</label>
<ul>
<li className="has-children">
<input type="checkbox" name ="sub-group-1" id="sub-group-1" />
<label htmlFor="sub-group-1">Sub Group 1</label>
<ul>
<li><a href="#0">Image</a></li>
<li><a href="#0">Image</a></li>
<li><a href="#0">Image</a></li>
</ul>
</li>
</ul>
</li>
</ul> );
}
}
export default MultiLevelAccordianMenu;
点击父母&#34; li&#34;元素,我想切换孩子&#34; ul&#34;元件。 我写了一个切换功能。在这个如何访问和设置子属性使隐藏和显示?
答案 0 :(得分:1)
您可以使用state并点击更改。只需将子元素的 className 动态化:
class MultiLevelAccordianMenu extends PureComponent {
constructor(props){
super(props);
this.state = {
isActive : false
};
this.toggleList = this.toggleList.bind(this);
}
toggleList(event){
this.setState({isActive: !this.state.isActive});
}
render(){
....
<li className="has-children" onClick={this.toggleList}>
.....
<ul className={this.state.isActive ? "active" : ""}>
....
}
并添加到您的css中:
ul{
visibility: hidden;
}
.active{
visibility: visible;
}
如果您想添加动画,可以使用css规则transition:
ul{
max-height: 0;
transition: max-height 0.15s ease-out;
overflow: hidden;
}
ul.active {
max-height: 500px;
transition: max-height 0.25s ease-in;
}