如何在React中使用scrollIntoView?

jcs*_*977 9 javascript reactjs

我试图使用我的标题中的链接滚动到我的应用程序的不同部分与scrollIntoView.标题是App的孩子.我收到一个TypeError说我试图保存id的变量是未定义的.有人可以帮我确定我做错了什么吗?我想我可能不得不使用ComponentDidMount,但我不知道该怎么做,如果这甚至是修复.我将不得不用我的所有标题链接执行此操作.

// ERROR bundle.js:152 Uncaught TypeError:无法在atClick(bundle.js:19957)的Object.actScrollLocations(bundle.js:152)处读取属性'scrollIntoView'为null.在Object.ReactErrorUtils.invokeGuardedCallback(bundle.js: 4660)在executeDispatch(bundle.js:4460)的executeDispatch(bundle.js:4483),executeDispatchesAndRelease(bundle.js:3913),executeDispatchesAndReleaseTopLevel(bundle.js:3924),位于forEachAccumulated(bundle.forEach)的executeDispatchesAndReleaseTopLevel(bundle.js:3924) .js:4760)at Object.processEventQueue(bundle.js:4129)///////

//应用

class App extends Component {
  constructor(props) {
    super(props);

    this.closeModal = this.closeModal.bind(this);
    this.openModal = this.openModal.bind(this);
    this.getScrollLocations = this.getScrollLocations.bind(this);

    this.state = {
      open: false,
      projects: Service,
      selectedProject: Service[0]
    }
  }

  closeModal(event) {
    this.setState({open: false});
  }

  openModal(project) {
    this.setState({
      open: true,
      selectedProject: project
    });
  }
    ///////////// scroll function //////////////
  getScrollLocations() {
    const whatIDo = document.getElementById('.whatIdo');
    console.log(whatIDo)
    whatIDo.scrollIntoView();
  }

  render() {
    const show = {
      display: 'block'
    };
    const hide = {
      display: 'none'
    };
    return (
      <div>
        <div style={this.state.open === false ? hide : show}>
          <Modal
            value={this.state.open}
            closeModal={this.closeModal}
            project={this.state.selectedProject}
          />
        </div>
        <Header
          //////////// FUNCTION PASSED TO HEADER ///////////////
          getScrollLocations={this.getScrollLocations}
        />
        <Intro />
        /////////////// ELEMENT I AM TARGETING /////////////////
        <WhatIDo id="whatIDo" />
        <WhoIAm />
        <Gallery
          value={this.state.open}
          projects={this.state.projects}
          openModal={this.openModal}
        />
        <Contact />
        <Footer />
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

//头

const header = (props) => {
  console.log(props);
  return (
    <div className="header">
      <div className="header-name">
         XXXXXXX XXXXXXX
      </div>

      <div className="header-links">
        <ul>
          <li>Intro</li>
          <li
            ///////////// FUNCTION CALL ON CLICK /////////////////
            onClick={() => props.getScrollLocations()}
          >What I do</li>
          <li>Who I am</li>
          <li>My Work</li>
          <li>Contact</li>
        </ul>
      </div>
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

Ant*_*gan 5

我使用以下模块在反应中实现此目的:

\n\n

https://www.npmjs.com/package/scroll-into-view-if-needed

\n\n

它的工作方式与您期望使用页内锚链接一样,并且可以毫无问题地与react-router一起使用。

\n\n
import React from \'react\';\nimport PropTypes from \'prop-types\';\n\nimport scrollIntoViewIfNeeded from \'scroll-into-view-if-needed\';\n\n/*\nSCROLL INTO VIEW\n\nPurpose:\n  This modular component enables hash links\n  eg. (www.xyz.com/somepage#someID)\n  and plays nice with react router 4\n\nUsage:\n  Wrap this component around a single div with an ID\n\nExample:\n  <ScrollIntoView  id={this.props.location.hash}>\n    <div id="someID">\n      ... loads of content...\n    </div>\n  </ScrollIntoView>\n\n  <a href="/somepage#someID"> IN-PAGE ANCHOR </a>\n\n */\n\nclass ScrollIntoView extends React.Component {\n\n\n  componentDidMount() {\n    this.scroll();\n  }\n\n  componentDidUpdate() {\n    this.scroll();\n  }\n\n  scroll() {\n    const { id } = this.props;\n    //console.log(\'ID is: \'+id);\n    if (!id) {\n      return;\n    }\n    const element = document.querySelector(id);\n    if (element) {\n      // this just jumps to the element\n      // see support:\n      //element.scrollIntoView({block: "end", behavior: "smooth"});\n\n      //If Firefox...\n      if (navigator.userAgent.indexOf("Firefox") > 0) {\n        //...use native smooth scrolling.\n        element.scrollIntoView({block: "end", behavior: "smooth"});\n      // If its any other browser, use custom polyfill...\n      }else{\n        //... luckily I have this handy polyfill...\n        scrollIntoViewIfNeeded(element, false, {\n          duration: 150\n        });\n        //  (\xe2\x8c\x90\xe2\x96\xa0_\xe2\x96\xa0\n      }\n    }\n  }\n\n  render() {\n    return this.props.children;\n  }\n}\nScrollIntoView.propTypes = {\n  id: PropTypes.string.isRequired,\n  children: PropTypes.oneOfType([\n    PropTypes.array.isRequired,\n    PropTypes.object.isRequired\n  ])\n};\nexport default ScrollIntoView;\n
Run Code Online (Sandbox Code Playgroud)\n\n

以下是实际操作的示例:\n https://anthonycregan.co.uk/portfolio

\n