我有以下两个组件:
为了可读性,我将在这个问题中跳过imports 和exports
资源管理器.js
const Explorer = () => {
const [selected, setSelected] = useState('C');
let dirArr = [
<Program key={"C"} name="C" isSelected={true}/>,
<Program key={"D"} name="D" isSelected={false}/>
];
const changeSelection = (newSelection) => {
if (selected !== newSelection){
dirArr = dirArr.map((el) => {
switch (el.props.name){
case newSelection:
case selected:
return <Program key={el.props.name} name={el.props.name} isSelected={!el.props.isSelected}/>
default:
return el
}
});
}
setSelected(newSelection);
}
const handleClick = (e) => {
//TODO: Make sure only <Program> allowed
changeSelection(e.target.parentNode.firstElementChild.innerHTML);
}
return (
<div onClick={handleClick}>
{dirArr}
</div>
)
}
基本上我想要做的是,点击取消选择上一个突出显示的组件并突出显示新的组件。
因此,在mapI'm 翻转isSelected道具上旧selected元素和newSelection
return <Program key={el.props.name} name={el.props.name} isSelected={!el.props.isSelected}/>
然后这里是Program.js
const Program = (props) => {
const [name, setName] = useState(props.name);
const [size, setSize] = useState(0);
const [date, setDate] = useState('01.01.75');
const selectedDeterminer = () => {
return props.isSelected ? { background: 'blue'} : {}
}
return (
<div style={selectedDeterminer()}>
<section className="program-name">{name}</section>
<section className="program-size">{size}</section>
<section className="program-date">{date}</section>
</div>
)
}
在控制台记录时,我确定我选择的是元素名称还是el.props.isSelected正确的名称,它只是在返回的地图上,它似乎不会影响结果
弑天下
相关分类