Prime React Dropdown筛选异常:Bootstrap模态框内输入框失焦求助
问题解决:PrimeReact Dropdown嵌套Bootstrap模态框后筛选焦点丢失
问题概述
使用PrimeReact的Dropdown组件在Bootstrap模态框内渲染地点列表,启用筛选功能后点击输入框焦点自动丢失,推测是模态框与下拉框的z-index冲突及Bootstrap焦点陷阱机制导致。
解决方案
1. 调整Dropdown面板的z-index层级
Bootstrap模态框默认z-index为1050,需确保PrimeReact下拉面板的层级更高,直接通过全局CSS覆盖:
.p-dropdown-panel { z-index: 1060 !important; }
避免用
onShow动态修改,DOM节点渲染时机滞后可能导致样式不生效。
2. 禁用Bootstrap模态框的焦点陷阱
Bootstrap模态框的focus trap机制会强制将焦点留在模态框内,导致Dropdown筛选框无法获取焦点,给Modal组件添加enforceFocus={false}属性:
<Modal show={showModal} onHide={closeModal} centered dialogClassName="modal custom-modal request-modal" id="upcoming-court" style={{ overflow: "visible" }} backdrop="static" tabIndex={-1} enforceFocus={false} // 添加此行 >
3. 修正Dropdown的optionLabel配置
因为locations是字符串数组,无需指定optionLabel(该属性针对对象数组),移除该属性避免渲染异常:
<Dropdown filter value={field.value || userLocation} onChange={(e) => { field.onChange(e.value); setUserLocation(e.value); }} options={locations} // 移除optionLabel="userLocation" placeholder="Select Location" className="select-bg w-100 list-sidebar-select" />
4. 利用Dropdown自带筛选(可选)
PrimeReact Dropdown的filter属性已自带搜索功能,无需额外维护filteredLocations和handleSearch,可直接简化代码。
修改后的核心Modal代码片段
<Modal show={showModal} onHide={closeModal} centered dialogClassName="modal custom-modal request-modal" id="upcoming-court" style={{ overflow: "visible" }} backdrop="static" tabIndex={-1} enforceFocus={false} > <div className="modal-dialog-centered"> <div className="modal-content"> <div className="modal-header d-flex justify-content-between align-items-center"> <h4>Enter Your Location</h4> </div> <div className="modal-body"> <button onClick={() => getUserLocation()} className="btn btn-primary mb-4" > <div className="d-flex gap-2 align-items-center"> {loading ? ( <ButtonLoader /> ) : ( <> <i className="feather-map-pin" /> <p className="m-0">Get My Location</p> </> )} </div> </button> <form autoComplete="off" className="w-100"> <div className="card-body-chat"> <div className="sorting-select"> <Controller name="userLocation" control={control} render={({ field }) => ( <Dropdown filter value={field.value || userLocation} onChange={(e) => { field.onChange(e.value); setUserLocation(e.value); }} options={locations} placeholder="Select Location" className="select-bg w-100 list-sidebar-select" /> )} /> </div> </div> </form> </div> </div> </div> </Modal>
内容的提问来源于stack exchange,提问作者Thunder_24
相关产品推荐
相关产品推荐

