Как переместить страницу в часть ссылки на «загрузку страницы»? - PullRequest
0 голосов
/ 07 января 2019

Я могу обнаружить изменение якоря следующим образом:

/ ScrollToPart:

import React from 'react';
import { withRouter } from 'react-router-dom';

class ScrollToPart extends React.PureComponent {

 componentDidMount() {
   // I want to scroll to the view.
   this.scroll();
 }

 componentDidUpdate(prevProps) {
  // Scroll when location changes.
  if (this.props.location !== prevProps.location) {
    this.scroll();
   }
  }

 scroll() {
   // Get the '#' id from the location 
   const id  = (
     this.props.location && this.props.location.hash
   ) ? this.props.location.hash : null;
    if (id) {
       element = document.getElementById(id.split('#').join(''));
       // If element present, scroll me to that part 
       if (element) {
         element.scrollIntoView();
       } else {
         // If element not present, scroll me to the top
         window.scrollTo(0, 0);
       }
     } else {
       // In no anchor element, scroll me to the top
       window.scrollTo(0, 0);
     }
   }

  render() {
    return this.props.children;
  }
 }
 export default withRouter(ScrollToPart);

Я вставил App в этот компонент так:

 <ScrollToPart>
   <App />
 </ScrollToPart>

В одном из компонентов в приложении, это список, который имеет

Субтитры:

    import PageSubtitle from '../PageSubtitle';
    import React from 'react';
    import { Link } from 'react-router-dom';

    class EmailList extends React.PureComponent {

      // This function is to get the existing Query parameters
      // and keep them as it is.
      getQueryParameterPath = () => {
        const { location } = this.props;
        const params = new URLSearchParams(location.search);


        let path = '/dashboard/emails?';
        if (params.get('my-page') && params.get('my-page').toString() !== '') {
          path = path + '&my-page=' + params.get('my-page');
        } 
        if (params.get('team-page') && params.get('team-page').toString() !== '') {
          path = path + '&team-page=' + params.get('team-page');
        }

        return path
      }

      render() {
        // This is the 'id' to which I need to move. It's just a 
        // string in its parent component.  
        // listId = 'my-list' and other time listId = 'team-list'
        const { listId } = this.props;

        return (
          <div id={listId}>
            <PageSubtitle 
              inline={true} 
              component={Link}
              to={`${this.getQueryParameterPath()}#${listId}`}
            >
              Title
            </PageSubtitle>
          </div>
        );
      }
    }

    export default EmailList; 

Так что теперь ../PageSubtitle

    import PropTypes from 'prop-types';
    import React from 'react';
    import Typography from '@material-ui/core/Typography';


    const PageSubtitle = ({ children, ...other }) => (
      <Typography
        variant="h6"
        {...other}
      >
        {children}
      </Typography>
    );

    export default PageSubtitle;

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

Я не могу перейти ни в один из разделов, когда загружается моя страница. element передается как ноль в компоненте ScrollToPart при загрузке / перезагрузке страницы.

Не могли бы вы помочь?

1 Ответ

0 голосов
/ 07 января 2019

Вот ответ,

просто установите таймер, пока он не найдет элемент. https://github.com/ReactTraining/react-router/issues/394#issuecomment-141526205

Надеюсь, это поможет

...