我正在根据 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>
);
}
但问题是在显示 Modal 之前调用了 componentDidMount 函数。我希望在模态显示后调用它
当 Modal 隐藏时,应该调用 componentWillUnmount。
最佳答案
您的显示样式不会阻止组件渲染,事实上,它必须渲染才能使显示样式发挥作用。
使用你的状态直接控制渲染..
<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>}
关于reactjs - 当我有 `display: none` 时,将调用 ComponentDidMount 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55154450/