![](/img/trans.png)
[英]React JS change component style on changing another component's state
[英]Change a react component's state on a click of another component
我試圖根據其狀態顯示/隱藏一個組件,並且我想在單擊第三個組件時對其進行更改。
//導航欄
export class NavigationBar extends React.Component {
constructor(props) {
super(props);
this.state = {
showNotification: false,
}
}
handleNotification = () => this.setState({
showNotification: !this.state.showNotification,
});
{ this.state.showNotification ? <Outside><Notifications /></Outside> : null}
//外部組件,負責檢測外部是否發生了點擊。
export default class Outside extends Component {
constructor(props) {
super(props);
this.setWrapperRef = this.setWrapperRef.bind(this);
this.handleClickOutside = this.handleClickOutside.bind(this);
}
componentDidMount() {
document.addEventListener('mousedown', this.handleClickOutside)
}
setWrapperRef(node) {
this.wrapperRef = node;
}
handleClickOutside(event) {
if(this.wrapperRef && !this.wrapperRef.contains(event.target)) {
console.log("clicked outside notifications");
this.setState({
showNotification: false
})
}
}
render() {
return (
<div ref={this.setWrapperRef}>
{this.props.children}
</div>
)
}
}
Outside.propTypes = {
children: PropTypes.element.isRequired
}
我的疑問是如何根據在Outside component
內部檢測到的事件來更改導航欄中的狀態?
在父級中,您需要向下到事件處理程序之外:
<Outside toggleNofitication={this.handleNotification}><Notifications /></Outside>
在外部,只需在事件觸發時調用toggleNofitication
:
handleClickOutside = () => {
// ...
this.props.toggleNofitication()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.