我希望能够使用 React 打开/关闭嵌套列表,以便在您单击父 li 时隐藏子项?这是我用来创建列表的内容。
列表.js
class List extends React.Component {
render(){
return (
<ul>
{this.props.list.map(function(item){
return (
<li>
<ListItem key={item.id} item={item} />
<List list={item.children} />
</li>
);
})}
</ul>
);
}
list-item.js
class ListItem extends React.Component {
handleCollapse(){
console.log('Open/Close: ' + this.props.item.display_name);
return false;
}
handleFilter(){
console.log('Filter id: ' + this.props.item.id);
return false;
}
render(){
return (
<div>
<a rel="{this.props.item.id}" onClick={this.handleCollapse.bind(this)}>
{this.props.item.display_name}
</a>
<input value="" type="checkbox" onClick={this.handleFilter.bind(this)} />
</div>
)
}
最佳答案
您是否在尝试模拟 Accordion 行为?如果是,那么您可以像这样修改您的代码。使用组件的状态并切换它以打开和关闭子组件。而不是创建 <List list={item.children} />
在 List
类,导入(或使用 require
) list.js
在 list-item.js
并渲染 child List
项目在当前的基础上ListItem's
状态。
list-item.js
class ListItem extends React.Component {
//Add this
constructor (){
super(...arguments);
this.state = { showChild:false};
}
handleCollapse(){
console.log('Open/Close: ' + this.props.item.display_name);
//Add this
this.setState({showChild:!this.state.showChild});
return false;
}
handleFilter(){
console.log('Filter id: ' + this.props.item.id);
return false;
}
render(){
let children;
if(this.state.showChild) {
children = (<List list={this.props.item.children} />);
}
return (
<div>
<a rel="{this.props.item.id}" onClick={this.handleCollapse.bind(this)}>
{this.props.item.display_name}
</a>
<input value="" type="checkbox" onClick={this.handleFilter.bind(this)} />
//Add this
{children}
</div>
)
};
}
列表.js
class List extends React.Component {
render(){
//Removed <List .../>, rest is same just other way of doing same stuff
let LI = this.props.list.map( (item) => {
return( <li> <ListItem key={item.id} item={item} /></li>);
}
);
return ( <ul>{LI}</ul>);
}
};
要测试的虚拟数据
var data=[
{
id:"1st of Level 1",
get display_name(){return _name(this.id,this.children)},
children: [
{
id:"1st of Level 1.2",
get display_name(){return _name(this.id,this.children)},
children: [
{
id:"1st of Level 1.2.1",
get display_name(){return _name(this.id,this.children)},
children:[]
}
]
},
{
id:"2nd of Level 1.2",
get display_name(){return _name(this.id,this.children)},
children:[]
}
]
},
{
id:"2nd of Level 1",
get display_name(){return _name(this.id,this.children)},
children:[]
},
{
id:"3rd of Level 1",
get display_name(){return _name(this.id,this.children)},
children:[]
},
{
id:"4th of Level1",
get display_name(){return _name(this.id,this.children)},
children:[]
}
];
function _name(id,child) {
if(child.length>0)
return("I am "+id+" I HAVE CHILDREN");
else {
return("I am "+id+" I DON'T HAVE CHILDREN ");
}
}
ReactDOM.render(<List list={data} />,document.getElementById('root'));
`
关于javascript - 在 React js 中打开和关闭递归嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35605008/