如何基于props控制元素渲染顺序实现搜索框图标左右对齐
无代码重复的实现方案
方案1:基于Bootstrap Flex原生CSS控制(优先推荐)
Bootstrap的input-group本身是Flex布局,直接用Flex的order属性控制元素顺序即可,完全不需要编写重复的JSX代码,性能最优、改动最小:
const SearchInput = ({ onClose, onChangeValue, searchIconPosition = 'left', // 新增props,可选值 left/right ...restProps }) => { return ( <div className='input-group'> <button className={`btn ${searchIconPosition === 'right' ? 'order-1' : ''}`} type='button' > <i className='bi bi-search'></i> </button> <Input className={`${searchIconPosition === 'right' ? 'order-0' : ''}`} placeholder='Search here...' onChangeValue={onChangeValue} {...restProps} /> {onClose && <i className='bi bi-x' onClick={onClose}></i>} </div> ); };
如果需要更精细的间距调整,也可以写少量自定义CSS替换Bootstrap的order工具类满足不了的场景。
方案2:调整DOM渲染顺序(适合必须修改DOM结构的场景)
如果因为SEO、无障碍适配等需求必须调整DOM节点的渲染顺序,把各个子元素抽成独立变量,根据条件拼接数组即可,完全没有重复代码:
const SearchInput = ({ onClose, onChangeValue, searchIconPosition = 'left', ...restProps }) => { // 抽离所有子元素,定义唯一key避免React渲染异常 const searchBtn = ( <button className='btn' type='button' key="search-btn"> <i className='bi bi-search'></i> </button> ) const inputEl = ( <Input placeholder='Search here...' onChangeValue={onChangeValue} {...restProps} key="search-input" /> ) const closeEl = onClose ? ( <i className='bi bi-x' onClick={onClose} key="close-icon"></i> ) : null // 根据位置参数组合子元素顺序 const children = searchIconPosition === 'left' ? [searchBtn, inputEl, closeEl] : [inputEl, searchBtn, closeEl] return ( <div className='input-group'> {children} </div> ); };
内容的提问来源于stack exchange,提问作者EshgheCode
相关产品推荐
相关产品推荐

