Css 在react中有条件地应用内联样式

Css 在react中有条件地应用内联样式,css,reactjs,Css,Reactjs,我在react中创建了我的组件上的一些画布菜单,现在它可以有条件地工作了。所以我有一个状态: constructor(props) { super(props); this.state = {isToggleOn: true}; this.toggleMenu = this.toggleMenu.bind(this); } componentDidMount() { this.setState({isToggleOn: false}); } toggleMe

我在react中创建了我的组件上的一些画布菜单,现在它可以有条件地工作了。所以我有一个状态:

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
    }));
}
我想让我的主体css溢出:隐藏当我的isToggleOn状态为true时,当它为false时,我想删除溢出:从主体隐藏。如何才能做到这一点

您可以添加componentDidUpdate生命周期钩子,在该钩子中检查isToggleOn是否在状态中更改,如果更改了,则更新正文溢出样式

componentDidUpdate(prevProps, prevState) {
  if (this.state.isToggleOn !== prevState.isToggleOn) {
    document.body.style.overflow = this.state.isToggleOn ? 'hidden' : 'visible';
  }
}
您可以添加一个componentDidUpdate生命周期钩子,在该钩子中检查isToggleOn是否在状态中更改,如果更改了,则更新正文溢出样式

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

可能的重复可能的重复将该逻辑放在CDU而不是toggleMenu中有什么好处吗?@giorgim OP还在CDM中切换状态,因此,考虑到状态在多个地方更新,我认为这是最直接的解决方案。将该逻辑放在CDU中而不是放在toggleMenu中有什么好处吗?@giorgim OP也在CDM中切换状态,因此我认为这是最直接的解决方案,因为状态在多个地方更新。