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

React中通过onClick点击事件动态创建HTML元素实现BMI结果展示

实现方案

你当前的代码有3个核心问题需要修正:

  • state中缺少存储历史BMI记录的数组,你之前用到的totals没有提前声明
  • 直接修改state(this.state.totals.push)不符合React的不可变数据规范,必须通过setState更新状态
  • BMI计算公式错误,正确逻辑是 体重(kg) ÷ (身高(m)的平方),你当前写的是体重加身高

具体修改步骤

  1. 在state中新增历史记录数组
    在constructor的state里加bmiRecords: [],用来存储每次计算的BMI结果
  2. 修正calculateBMI方法
    先做单位转换,计算正确的BMI值,再通过setState把新结果追加到历史记录数组中
  3. 在render方法底部渲染历史记录
    遍历bmiRecords数组,把每条结果渲染为你需要的<h3>格式

完整修正后的代码

import React, { Component } from 'react'

class Areas extends Component {
  constructor(props) {
    super(props)
  
    this.state = {
       kg: 0,
       height: 0,
       bmiRecords: [] // 新增存储历史BMI记录的数组
    }
    this.updateKG = this.updateKG.bind(this)
    this.updateHeight = this.updateHeight.bind(this)
    this.calculateBMI = this.calculateBMI.bind(this)
  }

  updateKG(event){
    this.setState({kg: Number(event.target.value)})
  }
  
  updateHeight(event){
    this.setState({height: Number(event.target.value)})
  }

  calculateBMI(){
    // 转换身高单位为米
    const heightInM = this.state.height / 100
    // 计算正确的BMI,保留两位小数
    const bmi = (this.state.kg / (heightInM * heightInM)).toFixed(2)
    // 不可变方式更新历史记录数组
    this.setState({
      bmiRecords: [...this.state.bmiRecords, bmi]
    })
  }
  
  
  render() {
    return (
      <div>
        <div className="jumbotron text-center mt-3">
          <div className="container">
            <h1 className="display-4">Calculate Your BMI</h1>
            <p className="lead">Calculate How fat you are ?</p>
          </div>
        </div>
        
        <div className="container mt-5">
          <div className="row">
            <div className="col text-center">
              <p>Your Kg</p>
              <input type="number" min="30" onChange={this.updateKG}/>
            </div>
            
            <div className="col text-center">
              <p>Your Height in cm</p>
              <input type="number" min="60" onChange={this.updateHeight}/>
            </div>
            
            <div className="col text-center">
              <p>Calculate Your BMI</p>
              <button className="btn btn-success" type="button" onClick={this.calculateBMI}>Submit</button>
            </div>
          </div>
        </div>

        {/* 新增历史BMI记录渲染区域 */}
        <div className="container mt-5">
          {this.state.bmiRecords.map((bmi, index) => (
            <h3 key={index}>你的身体质量指数为{bmi}</h3>
          ))}
        </div>
      </div>
    )
  }
}

export default Areas

补充说明

  • 给button修改了type为button,避免套form标签时误触发提交刷新页面
  • 存储输入值时提前转成了Number类型,避免后续计算出现字符串拼接问题
  • 用toFixed(2)把BMI保留两位小数,展示更友好
  • 遍历渲染列表时加了key属性,符合React的列表渲染规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 04:57:03