在React的一个大组件中,我想单击一个元素并滚动到另一个元素

问题描述 投票:0回答:1

在React中,我想单击一个元素并使页面滚动到另一个元素。我已经在Stack Overflow上看到了这个问题的答案,但是我不知道如何在一个大型组件(如我正在使用的组件)中实现它。

手术块埋在下面的组件中,但它们如下。应该滚动到元素的函数...const scrollToRef = (ref) => window.scrollTo(0, this.myRef.current)

在构造函数中创建Ref ...this.myRef = React.createRef()

我要单击的元素将滚动到所需的元素...<a onClick={executeScroll}>

我想滚动到的元素...<MyForm ref={this.myRef} />

如果我改变...const scrollToRef = (ref) => window.scrollTo(0, this.myRef.current)const scrollToRef = (ref) => window.scrollTo(0, 1400)我到达了想要的位置,但是当然,这不知道我要滚动到哪个元素,因此不适用于移动设备。

import React, { createRef } from 'react';
import Headroom from 'react-headroom'
import Fade from 'react-reveal/Fade';
import InfiniteScroll from 'react-infinite-scroll-component';
import HoverComp from './Hover'
import "animate.css/animate.min.css";
import ScrollAnimation from 'react-animate-on-scroll';
import MyForm from './myform'

import back from '../videos/tokyo_background.mp4'
import white from '../photos/white.jpg'
import fb_icon from '../photos/f.png'
import facebook_logo_white from '../photos/facebook-logo-white-c.png'
import z4881239_28446 from '../photos/84881239_2844929345568110_3163761343.png'


const scrollToRef = (ref) => window.scrollTo(0, this.myRef.current)   

export default class main extends React.Component {
  constructor(props) {
    super(props)
    this.myRef = React.createRef()
    this.displayName = 'Item';
    this.state = {
      apiResponse: [],
      page: 0,
      isHovered: {}
    }
  }

componentDidMount() {
  window.scrollTo(0, 70);
  this.callAPI();
}

handleMouseEnter = index => {
  this.setState(prevState => {
    return { isHovered: { ...prevState.isHovered, [index]: true } };
  });
};

handleMouseLeave = index => {
  this.setState(prevState => {
    return { isHovered: { ...prevState.isHovered, [index]: false } };
  });
};

callAPI() {
    fetch('/api/getList')
        .then(res => res.json())
        .then(res => this.setState({ apiResponse: res }))
}

loadMoreRows = () => {
  this.setState({ page: this.state.page + 1 })
}

  render() {
    const { apiResponse, page, isHovered } = this.state;

    const executeScroll = () => scrollToRef(this.myRef)

    if(!apiResponse) {
        return <p className="row">Loading</p>
    }
    return(
      <div className="App">
      <Headroom>
        <div className="header-container">
          <div className="header-background">
            <a href="/">
            <h2 className="house-icon">Home</h2>
            </a>
            <a onClick={executeScroll}>
              <h2 className="contact-text">Contact</h2>
            </a>
          </div>
        </div>
      </Headroom>

      <video autoPlay muted loop className="myVideo" src={back} type="video/mp4" />


        <div class="grid">
        <figure class="effect-romeo">
          <img src={white} alt="img05"/>
          <figcaption>
            <h2>Web <br/> <span>Design</span></h2>
            <p>We build websites large and small with the latest and greatest tools available</p>
          </figcaption> 
        </figure>
        <figure class="effect-romeo">
        <img src={white} alt="img05"/>
          <figcaption>
            <h2>Search <span>Optimization</span></h2>
            <p>We do everything possible to make you the number one search result</p>
          </figcaption> 
          </figure>
          <figure class="effect-romeo">
          <img src={white} alt="img05"/>
          <figcaption>
            <h2>Facebook <span>Integration</span></h2>
            <p>From Facebook Advertizing to creating and managing social media content</p>
          </figcaption> 
          </figure>
      </div>              

      <div className="image-grid">

        <div className='row'>
        <ScrollAnimation animateIn='bounceInRight' animateOnce={true}>
          <img className="house-icon" src={z4881239_28446}/>
            <div className='burb-box'>
              <p className='about-me-header'>About me</p>
              <p className='about-me'>
              </p>
            </div>
          </ScrollAnimation>
          <div className='contact-section'>
            <ScrollAnimation animateIn='bounceInLeft' animateOnce={true}>
              <MyForm ref={this.myRef} />
            </ScrollAnimation>
          </div>
          <div className="spacer"/>
          <img className="facebook-icon" src={fb_icon}/>
          </div>
          <ScrollAnimation animateIn='fadeIn' animateOnce={true}>

            <InfiniteScroll
              className='div-34x'
              dataLength={apiResponse.length}
              next={this.loadMoreRows}
              hasMore={true}
              >
              {Object.values(apiResponse.slice(0, (page+1)*6)).map((value, index) => 
              <a target="_blank" rel="noopener noreferrer" href={value.post}>
                <Child
                  onMouseEnter={() => this.handleMouseEnter(index)}
                  onMouseLeave={() => this.handleMouseLeave(index)}
                  isHovering={isHovered[index]}
                  src={value.image}
                  comment={value.comment}
                />
              </a>)}
            </InfiniteScroll>
            </ScrollAnimation>
          </div>
        </div>
    )
  }
}
function Child({ onMouseEnter, onMouseLeave, src, comment, isHovering }) {
  return (
      <div className="imagex" onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}>
        <HoverComp itemTitle={''} photoItemsProp={[src]}/>
        <div className="centered">
        {isHovering && comment}
        {isHovering && <img className='fb-image-icon' src={facebook_logo_white}/>}
        </div>
      </div>
  );
}
javascript reactjs dom
1个回答
0
投票

解决方案

您可以在不使用refs的情况下实现此目的。

首先,更新您的scrollToRef功能:

const scrollToElement = (target) => window.scrollTo(0, target.offsetTop);

最后,更新您的executeScroll功能:

const executeScroll = (element) => scrollToElement(element.target)

注意:

  • 您正在将myRef值形成为<MyForm ref={this.myRef} />。因此,当您执行scrollToRef(this.myRef)时,您的代码将滚动到该窗体。

  • 要继续使用引用,您需要为要滚动到的每个元素创建一个引用。例如:this.contactRef = React.createRef(); this.homeRef = React.createRef(); etc ...

  • 然后将这些引用附加到其适当的元素上:<a id="contact-link" ref={this.contactRef}>

  • 然后更新您的executeScroll函数以接受元素的引用const executeScroll = (ref) => {scrollToRef(ref)}

  • 最后,像这样调用您的onclick函数:onClick={() => executeScroll(this.contactRef)}

  • 前往docs,以了解有关ref和dom的更多信息。

  • [console.log()东西,如果您对梳理文档感到懒惰,则可以看到被抛出的数据。

© www.soinside.com 2019 - 2024. All rights reserved.