Я пытаюсь реализовать переадресацию Ref в своем демонстрационном проекте, но столкнулся с одной проблемой. Значение тока, исходящего из прямой ссылки, равно нулю, но как только я повторно визуализирую свой компонент NavBar (отправив опору), я получаю значение тока.
Мне в основном нужно прокрутить вниз до моего раздела, присутствующего в домашнем компоненте, из компонента NavBar. Это можно сделать, напрямую задав атрибут href и передав идентификатор. Но я хотел узнать, как работает forward ref и, следовательно, этот подход.
Может кто-нибудь помочь мне с этим?
Вот мой код.
import './App.css';
import NavBar from './components/NavBar/NavBar';
import Home from './components/Home/Home';
class App extends Component {
constructor(props) {
super(props);
this.homeRefService = React.createRef();
this.homeRefContact = React.createRef();
}
render() {
return (
<div className="App">
<NavBar name={this.state.name} homeRef={{homeRefService: this.homeRefService , homeRefContact: this.homeRefContact}}/>
<Home ref={{homeRefService: this.homeRefService, homeRefContact: this.homeRefContact }}/>
</div>
);
}
}
export default App;
**Home Component**
import React from 'react';
const home = React.forwardRef((props , ref) => {
const { homeRefService , homeRefContact } = ref;
console.log(ref);
return (
<div>
<section ref={homeRefService} id="Services">
Our Services
</section>
<section ref={homeRefContact} id="Contact">
Contact Us
</section>
</div>
)
})
export default home
**NavBar Component**
import React, { Component } from 'react'
export class NavBar extends Component {
render() {
let homeRefs = this.props.homeRef;
let homeRefServiceId;
let homeRefContactId;
if(homeRefs.homeRefService.current) {
homeRefServiceId = homeRefs.homeRefService.current.id;
}
if(homeRefs.homeRefContact.current ) {
homeRefContactId = homeRefs.homeRefContact.current.id;
}
return (
<div>
<a href={'#' + homeRefServiceId}> Our Services</a>
<a href={'#' + homeRefContactId }>Contact Us</a>
</div>
)
}
}
export default NavBar