【问题标题】:ComponentDidMount function is called when I have `display: none`当我有 `display: none` 时调用 ComponentDidMount 函数
【发布时间】:2019-03-14 03:20:52
【问题描述】:

我正在基于display 属性有条件地渲染一个模态组件。

我需要在组件show/hide上实现切换正文滚动功能。

参见下面的实现,

演示组件

<button onClick={()=> this.setState({ show: true })}>Show modal</button>
<Modal show={show} containerStyle={containerStyle} position={position} handleClickOutside={()=> this.setState({ show: false })} >
  <Content />
</Modal>

模态组件

componentDidMount() {
  disableBodyScroll(this.state.defaultMargin);
}

componentWillUnmount() {
  enableBodyScroll(this.state.defaultMargin);
}

render() {
  const { show } = this.props;
  const display = show ? 'block' : 'none';
  return (
    <div onClick={ handleClickOutside } className={ styles[ 'modal'] } style={ { display } }>
      {children}
    </div>
  );
}

但问题是在显示模态之前调用了 componentDidMount 函数。我希望在显示模态后调用它

并且在 Modal 隐藏时应该调用 componentWillUnmount。

【问题讨论】:

    标签: reactjs react-lifecycle


    【解决方案1】:

    您的显示样式不会阻止组件渲染,实际上它必须渲染才能使显示样式发挥作用。

    使用你的状态直接控制渲染..

    <button onClick={()=> this.setState({ show: true })}>Show modal</button>
    {this.state.show && <Modal show={show} containerStyle={containerStyle} position={position} handleClickOutside={()=> this.setState({ show: false })} >
      <Content />
    </Modal>}
    

    【讨论】:

    • 我需要处理Modal 组件中的componentDidMount。 Content 只是一些要渲染的node。请查看更新后的问题
    【解决方案2】:

    下列说法不正确:

    const display = show ? 'block' : 'none';
    

    应该是:

    const display = this.state.show ? 'block' : 'none';
    

    因为render范围内没有show,所以你想获取存储在state中的show的值,不是吗?

    【讨论】:

    • 我已经处理好了。
    猜你喜欢
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多