[英]change state for onClick event in other component react
我正在尝试使用道具传递状态,并且我想在按下另一个组件中的元素时将其更改为相反状态。 可能吗?
Header.js:
class Header extends Component {
constructor(props) {
super(props);
this.state = {
mobileOpen: false,
};
}
...
<Sidebar
open={this.state.mobileOpen}
/>
}
Sidebar.js:
function Sidebar({ open }) {
return (
<Navigation open={open} />)
}
Navigation.js:
class Navigation extends Component {
render() {
return (
<MenuItem onClick={/* change mobileOpen to false */}>text</MenuItem>
)
}
您可以将Header
组件中的回调作为道具传递给Sidebar
,而Sidebar
则将该回调作为道具传递给Navigation
。
在React中,您通常会区分表示组件和包含逻辑的组件(通常称为“容器组件”)。 您可以将所有状态放入其中,然后将必要的回调作为道具传递给表示组件。
在您的特定情况下,这将意味着:
Header.js:
class Header extends Component {
constructor(props) {
super(props);
this.state = {
mobileOpen: false,
};
}
// Create a callback to toggle the `mobileOpen` state
onMenuItemClicked = () => {
this.setState({mobileOpen: !this.state.mobileOpen});
}
render() {
return (
<Sidebar
open={this.state.mobileOpen}
/* pass callback to Sidebar */
onMenuItemClicked={this.onMenuItemClicked}
/>
);
}
}
Sidebar.js:
function Sidebar({ open, onMenuItemClicked }) {
return (
<Navigation
open={open}
/* pass callback from Header to Navigation */
onMenuItemClicked={onMenuItemClicked}
/>
);
}
Navigation.js:
class Navigation extends Component {
render() {
// finally use the callback
return (
<MenuItem onClick={() => this.props.onMenuItemClicked()}>text</MenuItem>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.