我有一个加号,onClick会切换为减号。这样,还可以基于切换显示成绩列表。
当前,当我单击插入符号时,所有元素都会展开,显示所有学生的列表。我只想切换特定学生的列表。
正在从API中提取数据,然后显示它们。
class Home extends Component {
constructor(props) {
super(props);
this.state = {
students: [],
search: "",
display: false
};
}
_iconOnClick = event => {
this.state.display ? this.setState({ display: false }) : this.setState({ display: true })
;
};
_renderDataFromAPI = () => {
//search filter
let filteredName = this.state.students.filter(student => {
return (
student.firstName
.toLowerCase()
.includes(this.state.search.toLowerCase()) ||
student.lastName.toLowerCase().includes(this.state.search.toLowerCase())
);
});
return filteredName.map((student,i) => {
let average =
student.grades.reduce((x, y) => parseInt(x) + parseInt(y)) /
student.grades.length;
return (
<div key={i}>
<div className="data">
<img className="img" src={student.pic} align="left" />
{this.state.display ? (
<FontAwesomeIcon
style={{
float: "right",
fontSize: "30px",
marginRight: "40px"
}}
icon="minus"
onClick={this._iconOnClick}
/>
) : (
<FontAwesomeIcon
style={{
float: "right",
fontSize: "30px",
marginRight: "40px"
}}
icon="plus"
onClick={this._iconOnClick}
/>
)}
<h1>
{student.firstName.toUpperCase()} {student.lastName.toUpperCase()}
</h1>
<p>Email: {student.email}</p>
<p>Company: {student.company}</p>
<p>Skill: {student.skill}</p>
<p>Average: {average}%</p>
<br />
{this.state.display ? (
<div >
{student.grades.map((grade, i) => {
return (
<p key={i}>
Test {i + 1}: {grade}%
</p>
);
})}
</div>
) : (
<div />
)}
</div>
<hr style={{ borderColor: "#e2e1e1" }} />
</div>
);
});
};
答案 0 :(得分:1)
将display
移动到每个学生。
let dataFromAPI = getDataFromAPI();
this.setState({
students: dataFromAPI.map(
student => Object.assign(student, { display: false })
});
显示列表...
{student.display ? (
<div >
{student.grades.map((grade, i) => { ...
切换显示/隐藏
_iconOnClick = id => {
let students = this.students.map(s => {
if (id == s.id) {
return Object.assign(s, { display: !s.display });
}
return s;
});
this.setState({ students });
};
...
<FontAwesomeIcon
style={{
float: "right",
fontSize: "30px",
marginRight: "40px"
}}
icon="minus"
onClick={this._iconOnClick(student.id)} />