React - how to pass state to another component

前端 未结 1 1152
悲哀的现实
悲哀的现实 2021-01-29 22:45

I\'m trying to figure out how to notify another component about a state change. Let\'s say I have 3 components - App.jsx,Header.jsx,and SidebarPush.jsx and all I\'m simply tryin

相关标签:
1条回答
  • 2021-01-29 22:54

    Move all of your state and your handleClick function from Header to your MainWrapper component.

    Then pass values as props to all components that need to share this functionality.

    class MainWrapper extends React.Component {
        constructor() {
            super();
            this.state = {
                sidbarPushCollapsed: false,
                profileCollapsed: false
            };
            this.handleClick = this.handleClick.bind(this);
        }
        handleClick() {
            this.setState({
                sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
                profileCollapsed: !this.state.profileCollapsed
    
            });
        }
        render() {
            return (
               //...
               <Header 
                   handleClick={this.handleClick} 
                   sidbarPushCollapsed={this.state.sidbarPushCollapsed}
                   profileCollapsed={this.state.profileCollapsed} />
            );
    

    Then in your Header's render() method, you'd use this.props:

    <button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>
    
    0 讨论(0)
提交回复
热议问题