[英]Reactjs Scroll with multiple ref
我對reactjs中的引用有疑問。 抱歉,這很蠢,但我仍在學習。 好吧,問題是我試圖滾動以使用ref做出反應,但我的問題是因為我想使用多個引用。
我的代碼是這樣的:
import React, { Component } from "react";
import './App.css';
import { Row, Col,Image,ListGroup,Button,Jumbotron,Container} from 'react-bootstrap';
class App extends Component {
constructor(props) {
super(props)
this.myRef = React.createRef()
this.myRef2 = React.createRef() // Create a ref object
}
handleOnClick = (event) => {
//.current is verification that your element has rendered
window.scrollTo(2, this.myRef2.current.offsetTop)
}
render() {
return (
<div className="App">
<button onClick={this.handleOnClick}>Click me</button>
<Row>
<Col className="menu text-center" lg ={4}>
<div className="picture" >
<Image src={process.env.PUBLIC_URL + '/Images/picture.jpg'} roundedCircle />
</div>
<h1 className="menu-name">Carlos Deseda</h1>
<h4 className="menu-office">Software Engineer - Web Developer</h4>
<div>
<Row>
<Col lg= {3}></Col>
<Col lg= {6} className="menu-text">
<ListGroup >
<ListGroup.Item>ABOUT</ListGroup.Item>
<ListGroup.Item>WORK EXPERIENCE</ListGroup.Item>
<ListGroup.Item>EDUCATION</ListGroup.Item>
<ListGroup.Item>SKILLS </ListGroup.Item>
<ListGroup.Item>CONTACT</ListGroup.Item>
</ListGroup>
</Col>
<Col lg= {3}></Col>
</Row>
</div>
</Col>
<Col className="info text-center" lg ={8}>
<div className="ref1" ref={this.myRef}> FirtsOne </div>
<div className="ref2" ref={this.myRef2}>SecondOne</div>
</Col>
</Row>
</div>
)}
}
export default App;
有了這個
this.myRef = React.createRef()
this.myRef2 = React.createRef()
我可以更改div的值並正常工作,但是我想知道是否可以像數組那樣僅將這兩個對象react.createRef()
一個react.createRef()
。 謝謝你的幫助!!
與其創建ref
像,
this.myRef = React.createRef()
您可以在構造函數中定義一個空數組,
constructor(props) {
super(props)
this.myRef = [];
}
現在,您可以使用callback ref
模式創建ref
,
<div className="ref1" ref={(ref) => { this.myRef[0] = ref }}> FirtsOne </div>
<div className="ref2" ref={(ref) => { this.myRef[1] = ref }}>SecondOne</div>
要滾動,您可以使用scrollIntoView
,
handleOnClick = (event) => {
//.current is verification that your element has rendered
console.log(this.myRef[1]);
this.myRef[1].scrollIntoView();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.