ReactJS引导程序折叠个人卡

时间:2020-11-10 18:02:12

标签: reactjs

ReacJS有一个关于单个折叠的示例:

function Example() {
  const [open, setOpen] = useState(false);

  return (
    <>
      <Button
        onClick={() => setOpen(!open)}
        aria-controls="example-collapse-text"
        aria-expanded={open}
      >
        click
      </Button>
      <Collapse in={open}>
        <div id="example-collapse-text">
          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus
          terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer
          labore wes anderson cred nesciunt sapiente ea proident.
        </div>
      </Collapse>
    </>
  );
}

render(<Example />);

但是说我要遍历一组对象,其中每个对象都是一张卡,并且我希望单击单个卡上的按钮只能打开该卡而不是所有卡。

目前我有这个:

return (
        <div>
          <div className='card-detail'>All Cards ({this.props.cardDetails.details.length})</div>
          {this.props.cardDetails.details.map((detail, index) => {
            return (
              <CardStyle key={index}>
                <Container>
                  <CardRow>
                    <FlexCol>
                      <Button onClick={() => this.setState({ open: !this.state.open })} 
                      aria-controls="example-collapse-text" 
                      aria-expanded={this.state.open} 
                      variant="light">Expand</Button>
                    </FlexCol>
                  </CardRow>
                </Container>
                <CardDetailInfo save={this.saveCard} confirm={this.confirmCard} open={this.state.open} detail={detail}></CardDetailInfo>
              </CardStyle>)
          })}
        </div>
      )


The collapse code is an other class; 

class CardDetailInfo extends Component {
  constructor(props) {
    super(props);
  }
  render() {
      return (
<Collapse in={this.props.open}>
</Collapse>
)

...

2 个答案:

答案 0 :(得分:0)

好的,所以我能够使用它:

...
  constructor(props) {
    super(props);
    this.state = {
      open: []    
    }
    this.handleClick = this.handleClick.bind(this);
  }
    componentDidUpdate(oldProps) {
      if(oldProps.open !== this.props.open) {
        this.setState({
          open: this.props.open
        });
      }
    }

  handleClick(event) {
    const id = event.target.id;
    let local_open = this.state.open;
    local_open[id] = !local_open[id]
    this.setState({open: local_open });
  }
...

<Button id={index} onClick={this.handleClick}
variant="light">Expand</Button>

In another class I use if statements

if (this.props.open.length == 0 || this.props.open[this.props.index]==false)
default view

if(this.props.open[this.props.index]==true)
expand view

答案 1 :(得分:-1)

要在每个<Collapse>中进行切换,或保持列表处于打开状态。 这里有一些选项:

1。一次合拢:

import React, { useState } from 'react';

function Collapse (props) {
  const [open, setOpen] = useState(props.in);
  
  useEffect(() => {
    setOpen(props.in);
  }, [props.in]);

  return (
     ...
  );
}

export default Collapse;

2。向cardDetails添加一个名为“打开”的新字段,并在需要时更改该属性。