2 回答
TA贡献1802条经验 获得超5个赞
我将单击处理程序向上移动一个级别:
import React, { useState } from "react";
function ListItem({ item, isActive, handleClick }) {
return (
<li
style={{ color: isActive && "green", cursor: "pointer" }}
onClick={() => handleClick(item)}
>
Item number {item}
{isActive && <span>×</span>}
</li>
);
}
function List({ itemList }) {
const [activeListItem, setActiveListItem] = useState();
const handleClick = (item) => activeListItem === item ? setActiveListItem() : setActiveListItem(item);
return (
<div>
<ul>
{
itemList.map(i => <ListItem key={i} item={i} handleClick={handleClick} isActive={activeListItem === item} />)
}
</ul>
</div>
);
}
TA贡献1840条经验 获得超5个赞
我认为您需要移动父组件中的状态,以便更好地管理每个项目的状态。
具有类组件的示例
import React, { Component } from "react";
class ListItem extends Component {
render() {
const isActive = this.props.activeIndex === this.props.item;
return (
<li
style={{ color: isActive && "green", cursor: "pointer" }}
onClick={() => this.props.onToggleSelect(this.props.item)}
>
Item number {this.props.item}
{isActive && <span>×</span>}
</li>
);
}
}
class List extends Component {
state = {
activeIndex: null,
};
onToggleSelect = (index) =>
this.setState({
activeIndex: index,
});
return (
<div>
<ul>
{
this.props.itemList.map(i => (
<ListItem
key={i}
activeIndex={this.state.activeIndex}
item={i}
onToggleSelect={onToggleSelect}
/>
))
}
</ul>
</div>
);
}
添加回答
举报