我希望统计组件只显示在点击后,我已经创建的3个按钮的任何一个.当我试图将统计组件移动到历史组件(在第二个返回中,下面的按钮按下历史:...)时,我现在面临着变量未定义的问题(好、中性、坏、ALL2都没有定义).如何使用我在一个组件中定义的变量,以便它可以在其他组件中使用?这是我的代码,
App.js
import { useState } from 'react'
const History = (props) => {
if (props.allClick.length === 0) {
return (
<div>
the app is used by pressing the buttons
</div>
)
}
return (
<div>
button press history: {props.allClick.join(' ')}
</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)
}
const all2 = good+neutral+bad
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>
<History allClick={allClick} />
<Statistic title="good" type={good}/>
<Statistic title="neutral" type={neutral}/>
<Statistic title="bad" type={bad}/>
<Statistic title="all" type={all2}/>
<Statistic title="positive" type={good/all2 * 100} />
</div>
)
}
export default App
Index.js
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
ReactDOM.createRoot(document.getElementById('root')).render(<App />)
帮助传递变量.可能是新的代码块.