我是一个编写 React 应用程序的初学者,当前包含三个组件,减去根应用程序(是的,这是一个在线类(class))。前两个并不重要,但对于名为 Total 的第三个,我需要返回练习计数的总和,这些练习计数定义为三个常量,exercise1~3。
我已经学会了如何对 props 进行求和,但仅限于 {props + props1 + props2...},我也可以做到,但随着零件和练习数量的增加,这不会很好。我可以减少这些值或编写一个辅助函数,但 React 的工作方式有点不同,我有点迷失如何为此提供一个良好的可扩展解决方案。
//first two components hidden
const Total = (props) => {
return (
<>
<p>help here!!</p>
</>
)
}
const App = () => {
const course = "Half Stack app development"
const part1 = "Fundamentals of React"
const exercises1 = 10 //this one
const part2 = "Using props to pass data"
const exercises2 = 7 //this one
const part3 = "State of a component"
const exercises3 = 14 //and this one
return (
<div>
<Header name={course} />
<Content name={part1} exercises={exercises1} />
<Content name={part2} exercises={exercises2} />
<Content name={part3} exercises={exercises3} />
<Total exercises= help here!! />
</div>
)
}
最佳答案
您应该将数据构建为对象数组。
const exercises = [{ name: 'Fundamentals of React', exercise: 10 }, etc];
在渲染中使用
exercises.map(ex => <Content name={ex.name} exercises={ex.exercise}/>)
对于总和,使用reduce https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
关于javascript - 如何对 React 组件值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57663559/