我正在尝试在React中创建一个webapp,在加载页面时将加载所有模块..当单击导航模块时,我想向下滚动到已选择的模块。 我有一个父模块,其中有和其他3个模块。我究竟做错了什么?我尝试用console.log进行案例:1看看有什么问题,但这似乎也不起作用。
App.js
class App extends Component {
constructor(props){
super(props);
this.MyStory = React.createRef();
this.Portfolio = React.createRef();
...
this.scrollToContent = this.scrollToContent.bind(this);
}
scrollToContent(content) {
switch(content) {
case 1:
this.MyStory.current.scrollIntoView({behavior: 'smooth'});
break;
case 2:
this.Portfolio.current.scrollIntoView({behavior: 'smooth'});
}
}
render() {
return (
<div className="App">
<Nav scrollToContent={this.scrollToContent} />
<MyStory scrollToTop={this.scrollToTop} ref={this.MyStory}/>
<Portfolio scrollToTop={this.scrollToTop} ref={this.Portfolio}/>
...
</div>
);
}
}
export default App;
MyStory.js
const MyStory = React.forwardRef((props, ref) => {
return (
<div className="story_box" ref={ref}>
<p> ....
</p>
</div>
);
});
export default MyStory;
Nav.js
...
class Nav extends Component {
constructor(props) {
super(props);
this.state = {
id: "slider",
};
}
onMenuClick = (event) => {
if (this.state.id === "slider"){
this.setState({id: "sliderOut"});
}
else (this.setState({id: "slider"}));
}
render () {
return (
<nav id="navigation" className={this.props.navStatus}>
<div className="links">
<a onClick={this.onMenuClick}>Menu</a>
<div id={this.state.id}>
<a id="myStory" onClick={this.scrollToContent}>My Story</a>
<a id="portfolio">Portfolio</a>
<a id="contact">Contact</a>
</div>
</div>
</nav>
);
}
}
导出默认导航;
答案 0 :(得分:0)
所以基本上我是如何解决的: 我已将导航移动到父应用程序,然后将ref =分配给了每个组件。 App.js
....
...
<a onClick={()=> {scrollToComponent(this.MyStory,{offset: 0, align: 'top', duration: 1000})}}>My Story</a>
...
<MyStory scrollToTop={this.scrollToTop} ref={(MyStory) => { this.MyStory = MyStory; }}/>
加载和滚动时,一切都在一页上!!! :)