英文:
How could I set/update a prop passed down to a React component from user input
问题
I have values in an array of objects that I wish to display as scoreBoard showing scores of two players after a number of sets in a game. I wish to have them in separate rows for the players. Thank you in anticipation.
The picture below shows scores after two sets.
How can I print the scores of each player in a separate row on the DOM?
Eg.
"player1Scores": 4 8 12
"player2Scores": 5 18 22
import React from "react"
import ReactDOM from "react-dom"
export default function App(){
const [players, setPlayers] = React.useState([{name: "Obi",
age: 44, achievements: [12, 4, 16, 28]}, {name: "Chiadi",
age: 47, achievements: [8, 10, 12, 21]}]);
const scores = players.map((player) => (player.achievements.map( (score, ind) => (<h2 key={ind}>{score}</h2>)
))
return ( {scores} )
}
ReactDOM.render(<App />, document.getElementById("root"))
英文:
I have values in an array of objects that I wish to display as scoreBoard showing scores of two players after a number of sets in a game. I wish to have them in separate rows for the players. Thank you in anticipation.
The picture below shows scores after two sets.
How can I print the scores of each player in a separate row on the DOM?
Eg.
"player1Scores": 4 8 12
"player2Scores": 5 18 22
import React from "react"
import ReactDOM from "react-dom"
export default funtion App(){
const [players, setPlayers] = React.useState([{name: "Obi",
age: 44, achievements: [12, 4, 16, 28]}, {name: "Chiadi",
age: 47, achievements: [8, 10, 12, 21]}]);
const scores = players.map((player) => (player.achievements.map( (score, ind) => (<h2 key={ind}>{score}</h2>)
))
return ( {scores} )
}
ReactDOM.render(<App />, document.getElementById("root"))
答案1
得分: 0
我通过将数组 player.achievements
传递给一个组件并进行映射来解决了这个问题。
const [players, setPlayers] = React.useState([{name: "Obi",
age: 44, achievements: [12, 4, 16, 28]}, {name: "Chiadi",
age: 47, achievements: [8, 10, 12, 21]}]);
const scores = players.map((player) => (
<ScoreComponent scores={player.achievements}/>
))
然后我能够在子组件 (ScoreComponent) 中映射 props.scores
并显示成就或分数。
英文:
I solved the problem by passing the array, player.achievements to a component and mapped through it.
const [players, setPlayers] = React.useState([{name: "Obi",
age: 44, achievements: [12, 4, 16, 28]}, {name: "Chiadi",
age: 47, achievements: [8, 10, 12, 21]}]);
const scores = players.map((player) => (
<ScoreComponent scores ={player.achievements}/>)
)
I was then able to map through props.scores in the child component (ScoreComponent) and have the achievements or scores displayed."
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论