【问题标题】:Conditionally applying inline style in react有条件地在反应中应用内联样式
【发布时间】:2019-08-05 07:07:28
【问题描述】:

我在我的组件上制作了一些画布菜单以做出反应,现在它可以有条件地工作。所以我有一个状态:

constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    this.toggleMenu = this.toggleMenu.bind(this);
}

componentDidMount() {
    this.setState({isToggleOn: false});
}

toggleMenu() {
    this.setState(prevState => ({
        isToggleOn: !prevState.isToggleOn
    }));
}

当我的 isToggleOn 状态为 true 并且当它为 false 时,我想将我的 body css overflow:hidden 中删除 overflow:hidden身体。怎样才能做到这一点?

【问题讨论】:

标签: css reactjs


【解决方案1】:

您可以添加一个componentDidUpdate 生命周期挂钩,检查isToggleOn 的状态是否发生变化,如果发生则更新主体overflow 样式。

componentDidUpdate(prevProps, prevState) {
  if (this.state.isToggleOn !== prevState.isToggleOn) {
    document.body.style.overflow = this.state.isToggleOn ? 'hidden' : 'visible';
  }
}

【讨论】:

  • 将该逻辑放入 CDU 而不是 toggleMenu 有什么好处吗?
  • @giorgim OP 也在 CDM 中切换状态,所以我认为这是最直接的解决方案,因为状态在多个地方更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-08
  • 2022-01-12
  • 1970-01-01
  • 2016-11-01
  • 2020-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多