反应-只切换一个按钮,而不是所有按钮 [英] React - toggle only one button, not all

查看:22
本文介绍了反应-只切换一个按钮,而不是所有按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有从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>
        )
    }
}

这篇关于反应-只切换一个按钮,而不是所有按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆