如何基于activeIndex实现子组件单选按钮点击时显示对应Tooltip
解决方案
核心思路是让每个子组件根据自身索引和父组件的activeIndex判断是否显示Tooltip,同时把每个选项对应的Tooltip内容传递给子组件,实现精准控制。
1. 调整父组件(Parent)
- 移除冗余的
showPopup状态,直接通过activeIndex控制显示逻辑 - 给子组件传递当前选项的索引(
currentIndex)和专属Tooltip内容(需确保options中包含对应字段) - 优化点击逻辑:点击同一按钮时切换Tooltip显示/隐藏,点击其他按钮时自动切换到对应Tooltip
修改后的父组件代码:
const [activeIndex, setActiveIndex] = useState(-1); return ( <div> {options?.map((option, index) => ( <RadioBtn key={index} label={option.label} value={option.value} currentIndex={index} activeIndex={activeIndex} tooltipContent={option.tooltipContent} // 每个选项的专属提示内容 onClick={() => { // 点击同一按钮时切换显示状态,点击不同按钮时切换到对应Tooltip setActiveIndex(prev => prev === index ? -1 : index); }} /> ))} </div> );
2. 修改子组件(RadioBtn)
- 接收
currentIndex、activeIndex和tooltipContent属性 - 计算
shouldShowTooltip:仅当activeIndex等于自身索引时显示Tooltip - 用
shouldShowTooltip控制Popup的open状态 - 使用父组件传递的
tooltipContent作为Tooltip内容
修改后的子组件代码:
const { currentIndex, activeIndex, tooltipContent } = props; const shouldShowTooltip = activeIndex === currentIndex; const popupMessage = tooltipContent ? (<div>{tooltipContent}</div>) : null; return ( <div> <Popup open={shouldShowTooltip}> <PopupPositionReference> <div onClick={props.onClick}> <input ref={iRef => { ref(iRef); inputRef.current = iRef; }} type="radio" checked={isChecked} {...props} {...rest} /> <label htmlFor={id}> {label} </label> </div> </PopupPositionReference> {popupMessage && <PopupContent>{popupMessage}</PopupContent>} </Popup> </div> );
补充说明
- 需确保
options数组中包含每个选项的Tooltip内容,示例格式如下:const options = [ { label: "选项1", value: "1", tooltipContent: "这是选项1的专属提示" }, { label: "选项2", value: "2", tooltipContent: "这是选项2的专属提示" }, // ...其他选项 ]; - 交互逻辑:点击单选按钮时,若Tooltip已显示则隐藏;若未显示则打开当前按钮的Tooltip,同时自动关闭其他按钮的Tooltip。
内容的提问来源于stack exchange,提问作者TSDev
相关产品推荐
相关产品推荐

