更改其他组件中onClick事件的状态

时间:2019-01-09 22:59:49

标签: javascript reactjs

我正在尝试使用道具传递状态,并且我想在按下另一个组件中的元素时将其更改为相反状态。有可能吗?

Header.js:

main.py

Sidebar.js:

from database import Base, db_session, engine
from models import User


def init_db():

    Base.metadata.create_all(bind=engine)

    db_session.add(
        User(username="testuser", password_hash=b"", password_salt=b"", balance=1)
    )
    db_session.commit()

    print("Initialized the db")


if __name__ == "__main__":
    init_db()

Navigation.js:

class Header extends Component {
  constructor(props) {
    super(props);

    this.state = {
      mobileOpen: false,
    };
  }
...
  <Sidebar
    open={this.state.mobileOpen}
    />
}

1 个答案:

答案 0 :(得分:0)

您可以将Header组件的回调作为道具传递给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>
    );
  }
}