Реагировать и Matchmedia - PullRequest
       6

Реагировать и Matchmedia

0 голосов
/ 03 декабря 2018

Я использую реагирующий контекстный API в компоненте mount для установки методов.Я также хотел бы использовать медиа-запрос там и установить метод для открытия или закрытия sidenav в зависимости от размера экрана.

Примерно так

 componentDidMount() {
    let context = this.context;
    let path = this.props.pageContext && this.props.pageContext.path;
    context.setSidenavLeaf(newPath)

// Below this is where I'd like to use the media query to set the sidenavOPen to false. Just not sure how to achieve that
  const match = window.matchMedia(`(max-width: 768px)`) 
if(match {
context.setSidenavOpen(false)
  }
}

Вид сбит с толку о том, какдостичь чего-то вроде этого.Я хочу вызвать метод и установить его на определенную точку прерывания носителя в моем компоненте монтируется.Который использует опору реакции пути маршрутизатора.Поэтому, если я нажму этот конкретный URL, отображаемый этим компонентом, и размер экрана будет таким, закройте sidenav, иначе оставьте его открытым.

1 Ответ

0 голосов
/ 03 декабря 2018

Вам необходимо прослушать событие изменения размера:

 componentDidMount() {
    let context = this.context;
    let path = this.props.pageContext && this.props.pageContext.path;
    context.setSidenavLeaf(newPath);

    // Below this is where I'd like to use the media query to set the sidenavOPen to false. Just not sure how to achieve that
    this.checkWidth = () => {
      const match = window.matchMedia(`(max-width: 768px)`);
      if (match) {
        context.setSidenavOpen(false);
      }
    };

    this.checkWidth();
    window.addEventListener("resize", this.checkWidth);
  }

  componentWillUnmount() {
    window.removeEventListener("resize", this.checkWidth);
  }

или добавьте слушатель к самому медиазапросу:

componentDidMount() {
    let context = this.context;
    let path = this.props.pageContext && this.props.pageContext.path;
    context.setSidenavLeaf(newPath);

    // Below this is where I'd like to use the media query to set the sidenavOPen to false. Just not sure how to achieve that
    this.match = window.matchMedia(`(max-width: 768px)`);
    this.checkWidth = (e) => {      
      if (e.matches) {
        context.setSidenavOpen(false);
      }
    };

    this.checkWidth(this.match);
    this.match.addListener(this.checkWidth);
  }

  componentWillUnmount() {
    this.match.removeListener(this.checkWidth);
  }
...