在 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>
);
}
最佳答案
解决方案
您无需使用引用即可实现此目的。
首先,更新您的 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()
如果您懒于梳理文档,可以使用这些东西来直观地了解周围的数据。
这是一个sandbox演示了如何使用 refs 和不使用 refs 来实现scrollTo。
关于javascript - 在 React 的一个大型组件中,我想单击一个元素并滚动到另一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60579804/