[英]How to hide a child component when changing React route
I have a dropdown BasketContents
component (as per this question ), which fades in and out when a button is clicked. 我有一个下拉的
BasketContents
组件(根据这个问题 ),当点击一个按钮时,它会淡入淡出。 I also want it to close when a the route is changed by clicking a Link
tag. 我还希望通过单击
Link
标记更改路径时关闭它。 Ie if it's already open on the Checkout
page, if I then click the Home
page link I want it to automatically close without clicking the basket's close button. 即如果它已经在
Checkout
页面上打开,如果我然后单击Home
链接我希望它自动关闭而不点击篮子的关闭按钮。
My Routes.js
is the root of the app: 我的
Routes.js
是应用程序的根目录:
render() {
return (
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="/home" component={Home} />
<Route path="/checkout" component={Checkout} />
</Route>
</Router>
);
}
App.js
looks in part like this: App.js
看起来像这样:
render() {
const childrenWithProps = React.Children.map(
this.props.children,
child => {
return (
React.cloneElement(child, {
basket: this.state.basket
}
)
)
}
);
return (
<div className="main">
<HeaderSection basket={this.state.basket} />
<div className="content">
{childrenWithProps}
</div>
</div>
)
}
The Basket.js
component contains the button: Basket.js
组件包含按钮:
constructor() {
super();
this.state = { open: false }
this.handleDropDown = this.handleDropDown.bind(this);
}
handleDropDown() {
this.setState({ open: !this.state.open })
}
render() {
return(
<div className="basket">
<button className="basketBtn" onClick={this.handleDropDown}>Toggle</button>
<BasketContents
contents={this.props.contents}
open={this.state.open}
/>
</div>
)
}
I did try adding onEnter
to my routes but understandably that doesn't do much since it doesn't have access to the Basket
's open
state. 我确实尝试添加
onEnter
到我的路线,但可以理解的是,由于它无法访问Basket
的open
状态,因此没有太大作用。 I would ideally like to set the open
state of Basket.js
to false
when changing route (ie when clicking on a Link
component). 理想情况下,在更改路径时(即单击
Link
组件时),将Basket.js
的open
状态设置为false
。 Is this possible? 这可能吗?
I found a solution that doesn't rely on context
. 我找到了一个不依赖于
context
的解决方案。 The first thing I did, following the React docs, was to lift my basket state up from the Basket
component to the App
component. 我遵循React文档做的第一件事就是将我的篮子状态从
Basket
组件提升到App
组件。 This made it easier to manipulate it from a central location. 这使得从中心位置更容易操作它。
Then, following a suggestion here , I listened for changes to the browserHistory
in the componentWillMount
hook in App
: 然后,按照这里的建议,我在
App
中的componentWillMount
钩子中听取了对browserHistory
更改:
componentWillMount() {
browserHistory.listen( () => {
this.setState({ basketOpen: false });
});
}
The result is that when the page changes the basket closes. 结果是当页面改变时篮子关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.