Как сделать первую вкладку аккордеона открытой по умолчанию React JS - PullRequest
1 голос
/ 08 января 2020

У меня в настоящее время есть компонент аккордеона, который работает хорошо, хотя мне нужно, чтобы первая вкладка была открыта по умолчанию (в настоящее время все вкладки закрыты по умолчанию). в настоящее время вы нажимаете «сводку», и она отображает содержимое ниже, изменяя «подробности», чтобы «открыть» как истинное. Я просто хочу, чтобы первый дочерний элемент был открыт по умолчанию - не всегда открытый, только при начальной загрузке, пока они не нажмут другую вкладку.

Ниже приведен код для компонента аккордеона:

class AccordionLight extends React.Component {
  constructor() {
    super();
    this.state = {
      open: -1
    };
  }

  render() {
    const { children, left, right } = this.props;
    const { open } = this.state;
    return (
      <div id="accordion-light">
        {children &&
          children.length > 0 &&
          children.map(child => {
            if (child.length) {
              child = child[0];
            }
            const { props } = child;
            if (props) {
              return (
                <details
                  key={props.label}
                  open={open && open.props && open.props.label === props.label}
                >
                  <summary
                    tabIndex={0}
                    role="tab"
                    onKeyPress={e => {
                      e.preventDefault();
                      this.setState({ open: open === child ? -1 : child });
                    }}
                    onClick={e => {
                      e.preventDefault();
                      this.setState({ open: open === child ? -1 : child });
                    }}
                  >
                    <h4>{props.label}</h4>
                    <p>{props.sub}</p>
                  </summary>
                  {child}
                </details>
              );
            }
            return '';
          })}
      </div>
    );
  }
}
AccordionLight.defaultProps = {
  children: null
};
AccordionLight.propTypes = {
  children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node])
};
export default AccordionLight;

1 Ответ

1 голос
/ 08 января 2020

Проверьте, хотите ли вы этого.

class AccordionLight extends React.Component {
  constructor() {
    super();
    this.state = {
      open: 0
    };
  }

  render() {
    const { children, left, right } = this.props;
    const { open } = this.state;
    return (
      <div id="accordion-light">
        {children &&
          children.length > 0 &&
          children.map((child, index) => {
            if (child.length) {
              child = child[0];
            }
            const { props } = child;
            if (props) {
              return (
                <details
                  key={props.label}
                  open={open === index}
                >
                  <summary
                    tabIndex={0}
                    role="tab"
                    onKeyPress={e => {
                      e.preventDefault();
                      this.setState({ open: index });
                    }}
                    onClick={e => {
                      e.preventDefault();
                      this.setState({ open: index });
                    }}
                  >
                    <h4>{props.label}</h4>
                    <p>{props.sub}</p>
                  </summary>
                  {child}
                </details>
              );
            }
            return '';
          })}
      </div>
    );
  }
}

ReactDOM.render(
  <AccordionLight>
    <p label="one label" sub="one sub">one body</p>
    <p label="two label" sub="two sub">two body</p>
    <p label="three label" sub="three sub">three body</p>
    <p label="four label" sub="four sub">four body</p> 
  </AccordionLight>,
  document.getElementById('app')
);

По сути, я отслеживал, какая вкладка в данный момент открыта в состоянии, и изначально установил для нее первый дочерний элемент

constructor() {
 super();
 this.state = {
   open: 0
 };
}
* 1006. * Затем проверьте open против index, чтобы увидеть, должна ли быть открыта текущая вкладка в map()
<details
 key={props.label}
  open={open === index}
>

Затем установите open на index выбранной вкладки

this.setState({ open: index });
...