React - toggle only one button, not all(反应-只切换一个按钮,而不是所有按钮)
本文介绍了反应-只切换一个按钮,而不是所有按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有从API呈现城市的应用程序,在每个城市下面应该有一个按钮来显示这个城市的描述。现在,当我单击一个按钮时,所有按钮都会更改文本并显示描述组件。
我看到了几个类似的问题,我知道,我可能应该使用索引来判断哪个按钮应该在单击时起作用,但是我在将其应用于我的代码时遇到了问题。
class CitiesList extends React.Component {
constructor(props) {
super(props);
this.state = {
opened: false,
}
this.toggleButton = this.toggleButton.bind(this);
};
toggleButton() {
const {opened} = this.state;
this.setState({
opened: !opened,
})
}
render() {
const items = this.props.cities.map((data, index) => (
<div key={index}>
<h2>{data.city}</h2>
<p>PM 2.5 value: {data.value} {data.unit}</p>
{this.state.opened ? <Button variant="outlined" color="primary" size="small" onClick={this.toggleButton}>Hide city description</Button> : <Button variant="outlined" color="primary" size="small" onClick={this.toggleButton}>Show city description</Button>}
{this.state.opened && <CityDescription/>}
</div>
));
return (
<div>
<div>
{items}
</div>
</div>
)
}
}
在CityDescription组件中,我现在只有:
class CityDescription extends React.Component {
render() {
return (
<div>
description
</div>
)
}
}
提前感谢您的帮助。
推荐答案
如@muhammad所述,您只需进行少量更改即可实现此功能。
以下代码应该可以工作:
class CitiesList extends React.Component {
constructor(props) {
super(props);
this.state = {
opened: false,
}
};
toggleButton = (index) => {
const {opened} = this.state;
this.setState({
opened: {
...opened,
[index]: !opened[index]
}
})
}
render() {
const { opened } = this.state;
const items = this.props.cities.map((data, index) => (
<div key={index}>
<h2>{data.city}</h2>
<p>PM 2.5 value: {data.value} {data.unit}</p>
{opened[index] ? <Button variant="outlined" color="primary" size="small" onClick={() => this.toggleButton(index)}>Hide city description</Button> : <Button variant="outlined" color="primary" size="small" onClick={() => this.toggleButton(index)}>Show city description</Button>}
{opened[index] && <CityDescription/>}
</div>
));
return (
<div>
<div>
{items}
</div>
</div>
)
}
}
这篇关于反应-只切换一个按钮,而不是所有按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:反应-只切换一个按钮,而不是所有按钮
基础教程推荐
猜你喜欢
- 带角度的选项卡:仅使用 $http 在单击时加载选项卡 2022-01-01
- HTML5 画布调整为父级 2022-01-01
- 即使每次插入第一个输入的值不同,第二个输入仍显示相同的输入值 2022-01-01
- 当木偶师打开Chrome时,不能使用Chrome扩展 2022-01-01
- 逻辑运算符 ||在 javascript 中,0 代表 Boolean false? 2022-01-01
- 最佳动态 JavaScript/JQuery 网格 2022-01-01
- 使用 jQuery 在悬停时交换 DIV 类 2022-01-01
- 在 Javascript 中使用 Fetch API 上传文件并显示进度 2022-01-01
- 从快速中间件中排除路由 2022-01-01
- CORS:当凭据标志为真时,无法在 Access-Control-Allow-Origin 中使用通配符 2022-01-01
