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
关键修改说明
- props传递:在App组件中调用History时,把
good、neutral、bad这些状态变量作为props传入 - 子组件接收并计算:History组件内部接收props,计算
all2和positive(添加all2>0的判断避免除以0) - 按需显示:利用原本的
allClick.length === 0判断,仅在有点击记录时渲染统计组件 - 优化显示:给positive添加
toFixed(1)保留一位小数,并加上百分号,显示更直观
内容的提问来源于stack exchange,提问作者Alexey Bondari
相关产品推荐
相关产品推荐

