Reactjs 滚动多个引用

Car*_*eda 4 javascript reactjs

我对reactjs中的ref有疑问。抱歉,这很愚蠢,但我仍在学习。好吧,问题是我正在尝试滚动以使用 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;
Run Code Online (Sandbox Code Playgroud)

有了这个

this.myRef = React.createRef()

this.myRef2 = React.createRef()
Run Code Online (Sandbox Code Playgroud)

我可以更改 div 的值并有效,但我想知道是否可以将这两个值加入到一个react.createRef()数组中,或者我不知道。谢谢你的帮助!!

rav*_*l91 7

而不是创造ref像,

this.myRef = React.createRef()
Run Code Online (Sandbox Code Playgroud)

您可以在构造函数中定义一个空数组,

constructor(props) {
    super(props)
    this.myRef = [];
}
Run Code Online (Sandbox Code Playgroud)

现在您可以使用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>
Run Code Online (Sandbox Code Playgroud)

要滚动,您可以使用scrollIntoView

handleOnClick = (event) => {
  //.current is verification that your element has rendered
  console.log(this.myRef[1]);
  this.myRef[1].scrollIntoView(); 
}
Run Code Online (Sandbox Code Playgroud)

演示