如果我在React中有一个元素列表,这些元素都调用附加到onClick
的相同函数,则可以说该函数附加了一个类,如何在不影响所有实例的情况下将该实例传递给该函数列出元素。
每次单击列表元素时,我所有的列表元素都会受到影响。
handleClick() {
this.setState({
expandedList: !this.state.expandedList
});
}
render() {
const folderStatus = this.state.expandedList ? 'expanded' : 'collapsed';
return (
<div className="container">
<ul>
{folders.map((folder, index) => (
<div onClick={() => this.handleClick()}
className= {folderStatus}
key= {index} >{folder}</div>
))}
</ul>
答案 0 :(得分:1)
以您的状态存储列表索引可能会达到目的:
handleClick = (index) => {
this.setState(prevState => ({
// Make sure you collapse when you click twice on the same row
selectedListIndex: prevState.selectedListIndex === index ? 'unclick' : index
}));
}
render() {
return (
<div className="container">
<ul>
{folders.map((folder, index) => (
<div onClick={() => this.handleClick(index)}
// Conditionally render the desired class
className= {this.state.selectedListIndex === index ? 'expanded' : 'collapsed'}
key= {index} >{folder}</div>
))}
</ul>
答案 1 :(得分:0)
handleClick(index) {
this.setState(prevState => ({
// Make sure you collapse when you click twice on the same row
selectedListIndex: prevState.selectedListIndex === index ? 'unclick' : index
}));
}
render() {
return (
<div className="container">
<ul>
{folders.map((folder, index) => (
<div onClick={this.handleClick.bind(this,index)}
// Conditionally render the desired class
className= {this.state.selectedListIndex === index ? 'expanded' : 'collapsed'}
key= {index} >{folder}</div>
))}
</ul>
在Felipa的答案中只是微小的变化。 onClick={this.handleClick.bind(this,index)}
如果我想在函数内部使用this
,我们也必须绑定this