我有三个组件Routes
,Menu
和一个Page
,并且我试图更新Page
(向下滚动到所选部分),当点击相应的菜单项时。
这是Routes
代码,其状态scrollDestination
作为道具传递给Page
,传递给setScrollDestination
的{{1}}方法也传递给Menu
作为道具。
export default class Routes extends React.Component {
constructor(props) {
super(props);
this.state = {
scrollDestination: '#part_1'
};
this.setScrollDestination = this.setScrollDestination.bind(this);
}
setScrollDestination(destination) {
this.setState({
scrollDestination : destination
})
}
render() {
return (
<Router onUpdate = {() => {document.body.scrollTop = 0}}>
<div className="router">
<Menu text = {this.props.text.header}
changeLang = {this.props.changeLang}
setScrollDestination = {this.setScrollDestination} />
<Switch>
<Route exact path = "/"
render = {(props) => (
<HomePage text = {this.props.text}
changeLang = {this.props.changeLang}
{...props} />
)} />
<Route path = "/page"
render = {(props) => (
<Page text = {this.props.text}
scrollDestination = {this.state.scrollDestination}
{...props} />
)} />
</Switch>
</div>
</Router>
);
}
}
Menu
组件将目标作为参数传递给setScrollDestination
函数,它正在更新路由&#39;州和Page
的道具。
export default class Menu extends React.Component {
constructor(props) {
super(props);
this.handleCloseClick = this.handleCloseClick.bind(this);
}
handlePageScroll(destination) { this.props.setScrollDestination(destination); }
render() {
return (
<div>
<ul>
<li onClick = {this.handlePageScroll.bind(this, '#part_1')}><Link to="/">Home</Link></li>
<li><Link to="/page">Page
<ul>
<li onClick = {this.handlePageScroll.bind(this, '#part_1')}>part_1</li>
<li onClick = {this.handlePageScroll.bind(this, '#part_2')}>part_2</li>
<li onClick = {this.handlePageScroll.bind(this, '#part_3')}>part_3</li>
</ul></Link>
</li>
</ul>
</div>
);
}
}
Page
组件只能滚动页面。州正在更新,但忽略了一些点击。它并不总是有效。
export default class Page extends React.Component {
constructor(props) {
super(props);
}
componentWillReceiveProps(nextProps) {
let scrollDestination = nextProps.scrollDestination;
setTimeout(function() {
TweenMax.to(window, 1, {scrollTo: {y:scrollDestination, offsetY:100}});
}, 400);
}
}
render() {
return (
<div id="part_1"></div>
<div id="part_2"></div>
<div id="part_3"></div>
);
}
}
我已经尝试了所有更新方法,所有这些方法都是一样的。哪个问题可以解决?
第二件事是,当ANY道具发生变化时,所有方法都会更新组件。如果一个特定道具改变了,有没有办法运行方法?
非常感谢您的回答。