gpt4 book ai didi

ReactJS 和 UIkit 3.6.5 : click event isn't fired inside modal window

转载 作者:行者123 更新时间:2023-12-04 08:22:14 25 4
gpt4 key购买 nike

我在 ReactJS 上开发了一个应用程序并尝试配置 U​​Ikit 模式窗口。问题是按钮(“保存”)上的点击处理程序不起作用,在模态窗口内基本上不监听点击事件。我将按钮放在模态窗口之外 - 单击事件有效(消息出现在控制台中)。这是一个错误还是我做错了什么?感谢关注!

return(
<>
<button
className="uk-button uk-button-primary uk-modal-close"
type="button"
onClick={() => console.log("Click")}>Save</button> {/* It works */}

<button className="uk-button uk-button-primary" uk-toggle="target: #modal-save">Publish</button>

<div id="modal-save" uk-modal="true">
<div className="uk-modal-dialog uk-modal-body">
<p>Save changes?</p>
<p className="uk-text-right">
<button className="uk-button uk-button-default uk-modal-close" type="button">Cancel</button>
<button
className="uk-button uk-button-primary uk-modal-close"
type="button"
onClick={() => console.log("Click")}>Save</button> {/* Doesn't work */}
</p>
</div>
</div>


</>

);

最佳答案

这个问题是由事件委托(delegate)的变化引起的(React 17) - https://reactjs.org/blog/2020/10/20/react-v17.html#changes-to-event-delegation
我用 Portals( https://reactjs.org/docs/portals.html ) 解决了这个问题,即

const ModalPortal = props => {
const modalRoot = document.createElement('div');
modalRoot.setAttribute('uk-modal', 'bg-close: false');
modalRoot.id = 'modal-save';

useEffect(() => {
document.body.appendChild(modalRoot);
return () => {
document.body.removeChild(modalRoot);
}
});

return ReactDOM.createPortal(props.children, modalRoot);
}

export default ModalPortal;
然后你应该将模态内容包装在父元素中
<ModalPortal>
// modal body
<span onClick={() => console.log('test')}>Test</span>
</ModalPortal>

关于ReactJS 和 UIkit 3.6.5 : click event isn't fired inside modal window,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65443562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com