You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用React的map()渲染Bootstrap 5网格时如何让等于按钮跨两行

实现方案

可以通过map()实现该需求,不需要手动编写所有行列元素,两种可选方案如下:

方案1:固定高度适配(兼容性最优)

核心利用Flex容器自动换行特性,给等于按钮设置两倍普通按钮高度,后续按钮会自动填充等于按钮左侧的剩余空间,仅需修改两处代码:

  1. map渲染时动态判断元素ID,给等于按钮的外层容器设置140px高度
  2. 把React的key属性移到map返回的最外层DOM元素上,符合React语法规范

修改后的完整代码如下:

class ButtonGrid extends React.Component { 
  constructor(props) { 
    super(props); 
    this.state={ currentButton: '' } 
    this.handleClick=this.handleClick.bind(this); 
  } 
  buttonGridArr=[ 
    { id: 'clear', text: 'C', grid: 'col-6 g-0' }, 
    { id: 'add', text: '+', grid: 'col-3 g-0' }, 
    { id: 'subtract', text: '-', grid: 'col-3 g-0' }, 
    { id: 'seven', text: '7', grid: 'col-3 g-0' }, 
    { id: 'eight', text: '8', grid: 'col-3 g-0' }, 
    { id: 'nine', text: '9', grid: 'col-3 g-0' }, 
    { id: 'multiply', text: 'x', grid: 'col-3 g-0' }, 
    { id: 'four', text: '4', grid: 'col-3 g-0' }, 
    { id: 'five', text: '5', grid: 'col-3 g-0' }, 
    { id: 'six', text: '6', grid: 'col-3 g-0' }, 
    { id: 'divide', text: '÷', grid: 'col-3 g-0' }, 
    { id: 'one', text: '1', grid: 'col-3 g-0' }, 
    { id: 'two', text: '2', grid: 'col-3 g-0' }, 
    { id: 'three', text: '3', grid: 'col-3 g-0' }, 
    { id: 'equals', text: '=', grid: 'col-3 g-0' }, 
    { id: 'zero', text: '0', grid: 'col-6 g-0' }, 
    { id: 'decimal', text: '.', grid: 'col-3 g-0' }
  ] 
  handleClick(event) { 
    this.setState(state=> ({ currentButton: event.target.value })); 
    console.log(this.state.currentButton); 
  } 
  render() { 
    return ( 
      <div className='container' id='button-grid' style={{borderStyle: 'solid', width: '350px', backgroundColor: 'black'}}> 
        <div className='row'> 
          {this.buttonGridArr.map(button=> ( 
            <div 
              key={button.id}
              className={button.grid} 
              style={{
                height: button.id === 'equals' ? '140px' : '70px', 
                borderStyle: 'solid', 
                borderWidth: '1px', 
                borderColor: 'black'
              }}
            >
              <button 
                type='button' 
                className='btn fw-bold w-100 h-100' 
                id={button.id} 
                value={button.text} 
                style={{color: 'white', borderRadius: '0px'}} 
                onClick={this.handleClick}
              >
                {button.text}
              </button>
            </div> 
          ))} 
        </div> 
      </div> 
    ); 
  } 
}

方案2:CSS Grid原生跨行(自适应能力更强)

如果使用Bootstrap 5.1及以上版本,可直接用原生CSS Grid布局实现跨行,不需要写死高度,适配性更强:

  1. 将父容器的row类替换为grid g-0,添加网格列配置gridTemplateColumns: 'repeat(4, 1fr)'
  2. 给等于按钮的外层容器添加gridRow: 'span 2'样式即可

内容的提问来源于stack exchange,提问作者Luke Worley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 17:27:04