React弹窗关闭后返回首页问题求助:如何停留在当前页面
解决React弹窗关闭后返回首页的问题
核心问题及修复方案
- 事件绑定错误:React事件采用驼峰命名规范,你在关闭按钮中使用了原生DOM的
onclick,需改为React的onClick。 - 按钮默认行为触发:未指定按钮
type时,浏览器默认将其识别为submit类型,若弹窗嵌套在<form>标签内,点击会触发表单提交,导致页面刷新跳转。需给关闭按钮添加type="button"属性。
修改后的Popup.js代码
function Popup(props) { return props.trigger ? ( <div className='popup'> <div className="popup-inner"> <button className='close-btn' type="button" onClick={() => props.setTrigger(false)} > Close </button> {props.children} </div> </div> ) : ""; } export default Popup
额外优化建议
你当前的两个弹窗共用同一个状态buttonPopup,点击任意一个按钮都会同时触发两个弹窗显示。建议为每个弹窗单独维护状态,示例如下:
// 在页面组件中声明独立状态 const [categoryPopup, setCategoryPopup] = useState(false); const [storePopup, setStorePopup] = useState(false); // 对应绑定按钮与弹窗 <button type="button" onClick={() => setCategoryPopup(true)} className="btn-small"> Analysis By Category </button> <Popup trigger={categoryPopup} setTrigger={setCategoryPopup}> {analysisResultByCategory} </Popup> <button type="button" onClick={() => setStorePopup(true)} className="btn-small"> Analysis By Store Name </button> <Popup trigger={storePopup} setTrigger={setStorePopup}> {analysisResultByDesc} </Popup>
内容的提问来源于stack exchange,提问作者user7087799
相关产品推荐
相关产品推荐

