@the5x

Как открыть/закрыть на кнопку вложенный список?

Есть список дерево, по клику на каждый элемент открывается и закрывается дерево. Вложенность может быть любая. Проблема в том, что есть две кнопки ОТКРЫТЬ и ЗАКРЫТЬ, которые открывают и закрывают все элементы. Как это реализовать не пойму. Вот есть код, который открывает элементы, а как сделать чтобы из любого состояния можно было ОТКРЫТЬ и ЗАКРЫТЬ не знаю. Подсткажите, ребята.

class Three extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      data,
      isExpand: false,
    }
  }

  openItem = () => {
    this.setState({
      isExpand: true,
    })
  }

  closeItem = () => {
    this.setState({
      isExpand: false,
    })
  }

  renderTree = (data) => {
    const { isExpand } = this.state

    return data.map(item => {
      const { id, title, children } = item

      return (
        <TreeItem
          key={id}
          id={id}
          title={title}
          isExpand={isExpand}
        >

          { Array.isArray(children) ? this.renderTree(children) : null }

        </TreeItem>
      )
    })
  };

  render() {
    const { data } = this.state;

    return(
      <>
        <button onClick={() => this.openItem()}>Open</button>
        <button onClick={() => this.closeItem()}>Close</button>

        { this.renderTree(data) }
      </>
    )
  }
}


и это дочерний компонент

class TreeItem extends React.Component{
    constructor(props) {
      super(props);

      this.state = {
        isExpand: this.props.isExpand,
      }
    }

    componentDidUpdate(prevProps) {
      const nextProps = this.props

      if(prevProps.isExpand !== nextProps.isExpand) {
        this.setState({
          isExpand: nextProps.isExpand
        })
      }
    }

    handleClick = () => {
      const { isExpand } = this.state;

      this.setState({
        isExpand: !isExpand,
      })
    }

    render() {
      const { isExpand } = this.state
      const { title, children } = this.props

      return (
        <ul>
          <li>
            <button
              onClick={() => this.handleClick()}
            >
              { isExpand
                ? `${title} Open`
                : `${title} Close`
              }
            </button>

            {
              <div className={ isExpand ? 'show' : 'hide' }>{ children }</div>
            }
          </li>
        </ul>
      )
    }
  }
  • Вопрос задан
  • 211 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы