人到中年有点甜
看看你的codsandbox,我已经通过重构解决了基本上,您想要处理父项中选定的项目,并将选择的项传递给您的子项。当您单击子项时,您可以使用作为 props 传递的 handleSelect 函数来告诉父项您更改了所选索引。然后在你的孩子中,你只需传递一个 bool 作为 props (isSelected) 测试所选索引是否等于 .map 当前实例中项目的索引所以只有一个孩子会得到这个布尔值的真值。然后,在您的 navevent 日期中,您可以重构有条件添加所选课程的方式。由于您不想传递空类,因此您可以使用此运算符&&。基本上,如果 isSelected 为 true ,它将应用所选的类,否则它将不会应用任何内容。我删除了第一个条件,因为我不明白你想要做什么,只留下 isSelected 作为参考。导航主控import React, { Component } from "react";//import "./Main.css";import NavEventDate from "./NavEventDate.js";export default class NavMain extends Component { constructor() { super(); this.state = { currentSelectedIndex: null, date: [ { day: 0, month: 0, year: 0, dayName: "" }, { day: 0, month: 0, year: 0, dayName: "" }, { day: 0, month: 0, year: 0, dayName: "" }, { day: 0, month: 0, year: 0, dayName: "" }, { day: 0, month: 0, year: 0, dayName: "" } ] }; this.GetOneDayFormat.bind(this); this.SetDate.bind(this); } componentDidMount() { let startDate = new Date(); this.SetDate(startDate); console.log(this.state.date); } SetDate(startDate) { let dates = this.state.date; for (let i = 0; i < 5; i++) { let currentDate = new Date(); currentDate.setDate(startDate.getDate() + i); dates[i].day = String(currentDate.getDate()); dates[i].month = String(currentDate.getMonth() + 1); dates[i].year = String(currentDate.getFullYear()); dates[i].dayName = String(this.GetOneDayFormat(currentDate)); } this.setState({ date: dates }); } GetOneDayFormat = (today) => { let dayNumber = today.getDay(); let dayName = ""; switch (dayNumber) { case 0: dayName = "Sunday".substring(0, 3); break; case 1: dayName = "Monday".substring(0, 3); break; case 2: dayName = "Tuesday".substring(0, 3); break; case 3: dayName = "Wednesday".substring(0, 3); break; case 4: dayName = "Thursday".substring(0, 3); break; case 5: dayName = "Friday".substring(0, 3); break; case 6: dayName = "Saturday".substring(0, 3); break; default: break; } return dayName; }; handleSelect = (index) => { this.setState({ currentSelectedIndex: index }); }; render() { return ( <nav id="sectionNav" class="datepicker event"> <div className="clearfix list-days"> <h1>Events</h1> <ul className="mobile-off"> {this.state.date.map((data, index) => ( <NavEventDate dayData={data} index={index} isSelected={this.state.currentSelectedIndex === index} handleSelect={this.handleSelect} /> ))} </ul> </div> </nav> ); }}导航事件日期import React, { useState, Component } from "react";//import "./Main.css";function NavEventDate({ dayData, handleSelect, index, isSelected }) { const dayToday = new Date(); return ( <li onClick={() => handleSelect(index)} className={isSelected && "selected"} data-date="20/11/2020" > <a href="#"> {dayData.dayName} <h1>{dayData.day}</h1> </a> </li> );}export default NavEventDate;如您所见,我仅添加了一个 css 属性来将所选项目项目符号变成黄色,以便您可以看到结果。如果您需要进一步解释,请告诉我。