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

时间:2019-03-14 11:43:16

标签: css reactjs

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

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

当我的overflow:hidden状态为 true 且为 false 时,我想使身体isToggleOn为我要删除{{1 }}来自正文。如何实现?

1 个答案:

答案 0 :(得分:6)

您可以添加一个componentDidUpdate生命周期钩子,以检查isToggleOn的状态是否已更改,并更新正文overflow的样式。

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