gpt4 book ai didi

javascript - 如果单击任何一个按钮,为什么所有 div 都会打开?

转载 作者:行者123 更新时间:2023-12-04 07:15:03 25 4
gpt4 key购买 nike

我正在尝试获取数据以将内容显示为前端。在这张图片中 enter image description here
你可以看到我提到了带有 div 属性的按钮,即蓝色。我尝试了下面的代码,但我不知道如何创建/处理按钮和 div。

import React from "react";
import {Col } from "react-bootstrap";
import "./style.scss"

class Example extends React.Component{

constructor(props){
super(props);
this.state = {
opencollapse: true,
}
}

toggle = () => this.setState((currentState) => ({opencollapse: !currentState.opencollapse}));


renderApps = () => {
const result = this.props.userdata.appliers.map((item, i) => {
return(
<div key={i}>
<div>
<div className="d-flex">
<Col>
<button onClick={this.toggle}>{this.state.opencollapse ? 'Click to close' : 'See Letter'}</button>
</Col>
<Col>
helloIcon
</Col>
</div>
{this.state.opencollapse && <div>{this.props.userdata.appliers[i].letter}</div>}
</div>
</div>
)
});
return result;
}

render(){

return (
<div>
{this.renderApps()}
</div>
);
}
}

export default Example;

我不知道我哪里做错了。
在图像中,如您所见,我尝试单击第三个按钮以打开第三个 div,但 1 号和 2 号按钮也被打开。我想打开那些由我打开的div,让其他人关闭。如果我点击第一个按钮,那么第一个 div 应该打开,其余的应该关闭,反之亦然。

最佳答案

这是因为所有按钮都有相同的状态变量。
您可以创建另一个组件。
然后每个映射的组件将有自己的状态

子组件:

import React from "react";
import {Col } from "react-bootstrap";
import "./style.scss"

class ChildExample extends React.Component{

constructor(props){
super(props);
this.state = {
opencollapse: true,
}
}

toggle = () => this.setState((currentState) => ({opencollapse: !currentState.opencollapse}));

render(){

return (
<div>
<div>
<div className="d-flex">
<Col>
<button onClick={this.toggle}>{this.state.opencollapse ? 'Click to close' : 'See Letter'}</button>
</Col>
<Col>
helloIcon
</Col>
</div>
{this.state.opencollapse && <div>{this.props.text}</div>}
</div>
</div>
);
}
}

export default ChildExample;
示例组件中的 renderApps 函数:
renderApps = () => {
const result = this.props.userdata.appliers.map((item, i) => {
return(
<ChildExample text={this.props.userdata.appliers[i].letter}
)
});
return result;
}

关于javascript - 如果单击任何一个按钮,为什么所有 div 都会打开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68817150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com