我正在使用reactstrap中的UncontrolCollapse组件,并且我要控制多个静态元素。
默认情况下,我需要默认打开所有元素(不折叠),单击相关的单个元素将被折叠。
但是我只有一种状态可以管理该行为,它将在单击时打开和关闭所有面板。
下面是代码:
import { UncontrolledCollapse, Button, CardBody, Card } from "reactstrap";
class ProductList extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
isOpen: true
};
}
toggle() {
this.setState({
isOpen: !this.state.isOpen
});
}
render() {
return (
<div>
<div
className="filter-options-title"
id="toggler"
onClick={this.toggle}
>
Test
</div>
<UncontrolledCollapse toggler="#toggler" isOpen={this.state.isOpen}>
<div className="filter-options-content">Test Content</div>
</UncontrolledCollapse>
<div
className="filter-options-title"
id="toggler1"
onClick={this.toggle}
>
Test
</div>
<UncontrolledCollapse toggler="#toggler1" isOpen={this.state.isOpen}>
<div className="filter-options-content">Test Content</div>
</UncontrolledCollapse>
</div>
);
}
}
答案 0 :(得分:0)
您需要在您的状态下创建单独的密钥。因为当前您对两个元素都使用相同的状态道具,所以如果您关闭一个元素,那么两个元素都会被关闭。我还更改了切换方法(接受接受哪些元素被切换)。
import { UncontrolledCollapse, Button, CardBody, Card } from 'reactstrap';
class ProductList extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
toggler: true,
toggler1: true,
}
}
toggle(toggler) {
let togglerStatus = this.state[toggler]; //check the status of the toggle you clicked
this.setState({
[toggler]: !togglerStatus // change the status only for the toggle you clicked
});
}
render() {
return (
<div>
<div className="filter-options-title" id="" onClick={() => this.toggle('toggler')}>
Test
</div>
<UncontrolledCollapse toggler="#toggler" isOpen={this.state['toggler']}>
<div className="filter-options-content">
Test Content
</div>
</UncontrolledCollapse>
<div className="filter-options-title" id="toggler1" onClick={() => this.toggle('toggler1')}>
Test
</div>
<UncontrolledCollapse toggler="#toggler1" isOpen={this.state['toggler1']}>
<div className="filter-options-content">
Test Content
</div>
</UncontrolledCollapse>
</div>
)
}
}