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

React组件间属性传递求助:Statistic组件变量未定义

解决React组件间变量传递与统计组件按需显示问题

要实现点击按钮后才显示统计组件,同时解决子组件无法访问父组件变量的问题,核心是通过props把父组件的状态变量传递给子组件,具体修改如下:

修改后的App.js代码

import { useState } from 'react'

const History = (props) => {
  const { allClick, good, neutral, bad } = props
  const all2 = good + neutral + bad
  // 处理除以0的情况,避免出现NaN
  const positive = all2 > 0 ? (good / all2 * 100).toFixed(1) : 0

  if (allClick.length === 0) {
    return (
      <div>
        the app is used by pressing the buttons
      </div>
    )
  }

  return (
    <div>
      <div>button press history: {allClick.join(' ')}</div>
      <Statistic title="good" type={good}/>
      <Statistic title="neutral" type={neutral}/>
      <Statistic title="bad" type={bad}/>
      <Statistic title="all" type={all2}/>
      <Statistic title="positive" type={`${positive}%`}/>
    </div>
  )
}

const Button = (props) => {
  return (
    <div>
      <button onClick={props.handleClick}> {props.text} </button>
    </div>
  )
}

const Statistic = (props) => {
  return (
    <div>
      <p>{props.title}: {props.type}</p>
    </div>
  )
}

const App = () => {
  // save clicks of each button to its own state
  const [good, setGood] = useState(0)
  const [neutral, setNeutral] = useState(0)
  const [bad, setBad] = useState(0)
  const [allClick, setClick] = useState([])

  const inlineButton = {
    display: 'inline-flex',
    gap: '10px'
  }

  const goodClick = () => {
    setClick(allClick.concat('G'))
    setGood(good + 1)
  }

  const neutralClick = () => {
    setClick(allClick.concat('N'))
    setNeutral(neutral + 1)
  }

  const badClick = () => {
    setClick(allClick.concat('B'))
    setBad(bad + 1)
  }

  return (
    <div>
      <h1> give feedback </h1>
      <div style={inlineButton}>
        <Button handleClick={goodClick} text="good"/>
        <Button handleClick={neutralClick} text="neutral"/>
        <Button handleClick={badClick} text="bad" />
      </div>

      <h1> statistics </h1>

      {/* 将需要的状态变量通过props传递给History组件 */}
      <History 
        allClick={allClick} 
        good={good} 
        neutral={neutral} 
        bad={bad} 
      />
    </div>
  )
}

export default App 

关键修改说明

  1. props传递:在App组件中调用History时,把good、neutral、bad这些状态变量作为props传入
  2. 子组件接收并计算:History组件内部接收props,计算all2和positive(添加all2>0的判断避免除以0)
  3. 按需显示:利用原本的allClick.length === 0判断,仅在有点击记录时渲染统计组件
  4. 优化显示:给positive添加toFixed(1)保留一位小数,并加上百分号,显示更直观

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 22:07:47