我有以下两个组件:为了可读性,我将在这个问题中跳过imports 和exports资源管理器.jsconst 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.jsconst 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正确的名称,它只是在返回的地图上,它似乎不会影响结果
1 回答
弑天下
TA贡献1818条经验 获得超8个赞
我想问题在于您使用的是静态isSelected道具 - 您需要使用状态selected变量:
let dirArr = [
<Program key={"C"} name="C" isSelected={selected === 'C'}/>,
<Program key={"D"} name="D" isSelected={selected === 'D'}/>
];
添加回答
举报
0/150
提交
取消