反应-只切换一个按钮,而不是所有按钮

人气:892 发布:2022-10-16 标签: javascript dictionary onclick reactjs toggle

问题描述

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

765