为何React Bootstrap Modal内绑定React Select的ref始终为null?
ref值始终为null的原因及解决方案
核心原因
- React-Bootstrap Modal 默认懒加载子元素:默认配置下,Modal 仅在
show属性为 true 时才会渲染内部嵌套的子组件,如果你在 Modal 未激活展示的状态下读取testRef.current,此时 Select 组件还未挂载到 DOM 树,ref 自然为 null。 - react-select 版本兼容问题:如果你使用的是 react-select v2 及更早版本,普通
ref属性不会绑定到组件实例上,需要使用专属的innerRef属性传递 ref;如果是 v3 及以上版本,若需要获取内部 input 节点而非组件实例,需要从返回的实例中取input属性。
修复方案
代码示例
import React, { useRef, useEffect } from 'react'; import Select from "react-select"; import { Modal } from "react-bootstrap"; function TestModal ({modalProps, selectProps}) { const testRef = useRef(null); // 仅在Modal展示后访问ref,避免取到null useEffect(() => { if(modalProps.show) { console.log(testRef.current); // 这里可以正常操作ref } }, [modalProps.show]) return ( {/* 加renderOnMount属性让Modal初始化时就渲染子元素,不需要等show为true */} <Modal {...modalProps} renderOnMount={true}> {/* react-select v2及以下把ref换成innerRef={testRef} */} <Select {...selectProps} ref={testRef} /> </Modal> ) }
内容的提问来源于stack exchange,提问作者Keir
相关产品推荐
相关产品推荐

