问题描述
我目前正在学习ReactJS,并且在尝试隐藏/显示div时遇到问题!以下代码有效,但是当我单击“了解更多”按钮时,它会隐藏每张卡上的每个描述,但是我只想在单击它的地方显示/隐藏该描述。
import Axios from 'axios';
import React,{ useEffect,useState } from 'react';
import JobApplicationList from './JobApplicationList';
import Card from "react-bootstrap/Card";
import ScriptTag from 'react-script-tag';
export default class Home extends React.Component{
constructor(){
super()
this.state={
showMe:true,advLists: []
}
}
operation(){
this.setState({
showMe:!this.state.showMe
})
}
componentDidMount() {
Axios.get(`http://localhost:3001/get/adv`)
.then(res => {
const advLists = res.data;
this.setState({ advLists });
})
}
render(){
return (
<div className="main-page">
<div className="adv_container">
{this.state.advLists.map((val,key) => {
return (
<div className="card_">
<Card style={{ width: "100%" }}>
<Card.Body>
<Card.Title>{val.compName}</Card.Title>
<Card.Subtitle className="mb-2 text-muted">
{val.city} | {val.compWebsite}
</Card.Subtitle>
<Card.Subtitle className="mb-2 text-muted">
{val.salaire} €
</Card.Subtitle>
{ this.state.showMe?
<div className="description">
<Card.Text>{val.description}</Card.Text>
</div>
:null
}
<Card.Link onClick={()=> this.operation()} id="toto" href="#">Learn more</Card.Link>
<Card.Link href="#">Apply</Card.Link>
</Card.Body>
</Card>
</div>
);
})}
</div>
</div>
)
}
}
我有点知道出了什么问题,当我按下按钮时,会为每张卡提供showMe状态,但我不知道如何解决! 预先感谢您的帮助。
解决方法
将初始showMe
状态设置为空,然后转换operation
以获取要切换的索引。如果索引已保存到状态,则将其设置回null。
operation(index) {
this.setState({
showMe: this.state.showMe === index ? null : index,})
}
使用映射的索引传递到处理程序,并针对showMe
状态检查该索引以显示卡。
{this.state.advLists.map((val,key) => {
return (
<div className="card_">
<Card style={{ width: "100%" }}>
<Card.Body>
<Card.Title>{val.compName}</Card.Title>
<Card.Subtitle className="mb-2 text-muted">
{val.city} | {val.compWebsite}
</Card.Subtitle>
<Card.Subtitle className="mb-2 text-muted">
{val.salaire} €
</Card.Subtitle>
{this.state.showMe === key && ( // <-- check if index/key matches
<div className="description">
<Card.Text>{val.description}</Card.Text>
</div>
)}
<Card.Link
onClick={() => this.operation(key)} // <-- pass key/index to toggle
id="toto" href="#"
>
Learn more
</Card.Link>
<Card.Link href="#">Apply</Card.Link>
</Card.Body>
</Card>
</div>
);
})}
,
我可以为您提供有关如何使用React类组件切换单个项目的代码模式。
class MyComponent extends React.Component {
state = { items: [] }; // initial state
componentDidMount() {
// fetched data
this.setState({ items: [{ title: "one" },{ title: "two" }] });
}
toggleItem = (index) => {
let items = this.state.items;
items[index].hidden = !items[index].hidden; // mutating
this.setState({ items }); // new object triggers re-render
};
render() {
return (
<ul>
{this.state.items.map((item,index) => {
return (
<li key={index}> {/* remember to use a key */}
<button onClick={() => this.toggleItem(index)}>toggle</button>
{!item.hidden && item.title}
</li>
);
})}
</ul>
);
}
}