当我有“display: none”时,将调用 ComponentDidMount 函数

Kul*_*mte 2 reactjs react-lifecycle

我正在根据属性有条件地渲染模态组件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>
Run Code Online (Sandbox Code Playgroud)

模态组件

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

Run Code Online (Sandbox Code Playgroud)

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

当 Modal 隐藏时,应该调用 componentWillUnmount 。

lec*_*tor 5

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

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

<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>}
Run Code Online (Sandbox Code Playgroud)