简体   繁体   中英

change state for onClick event in other component react

I am trying to pass state using props and I would like to change it inverse when I press an element in another component. is it possible?

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>
    )
}

You can pass a callback from the Header component as a prop to Sidebar which in turn passes that callback to Navigation as a prop.

In React you usually have a differentiation between presentation components and components containing logic (often referred to as "container components"). You can put all the states in there and and pass the necessary callbacks as props to the presentation components.

In your specific case, this would mean something like this:

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>
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM