我正在尝试将两个变量从组件“游戏”发送到组件“应用程序”,但我不确定如何一次发送多个 Prop 。
这是我所拥有的:
//App Component
class App extends Component {
constructor(props) {
super(props)
this.state = {
score: 0,
}
this.changeScore = this.changeScore.bind(this)
}
changeScore(newScore) {
this.setState(prevState => ({
score: prevState.score + newScore
}))
}
render() {
return(
<div>
<Game onClick={this.changeScore}/>
<Score score={this.state.score}/>
</div>
)
}
}
//Game Componenet
class Game extends Component {
constructor(props) {
super(props)
this.state = {
score: 0,
}
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
console.log('Clicked')
this.props.onClick(this.state.score)
}
render() {
return(
<div>
<button onClick={this.handleClick}> Score Button </button>
</div>
)
}
}
//Score Component
class Score extends Component {
render() {
const score = this.props.score
return(
<div>
<h1>Score: {score}</h1>
</div>
)
}
}
有了这个,我可以将 Prop “分数”从“游戏”发送到“应用程序”,但我想知道是否有可能发送比一个 Prop 更多的 Prop ,例如“分数”和一个新变量,使用相同的按钮按下“count”,最终能够在“Score”Componenet 中同时显示“score”和“count”。
谢谢。
最佳答案
当然可以,只需更新您在 Parent App 组件中定义的函数以接受两个参数。
App.js
class App extends Component {
constructor(props) {
super(props)
this.state = {
score: 0,
count: 0
}
this.changeScore = this.changeScore.bind(this)
}
changeScore(newScore, count) {
this.setState(prevState => ({
score: prevState.score + newScore,
count: prevState.count + count
}))
}
render() {
return(
<div>
<Game
onClick={this.changeScore}
score={this.state.score}
count={this.state.count}
/>
<Score score={this.state.score} count={this.state.count}/>
</div>
)
}
}
Game.js//重构,因为它不需要使用状态
const Game = ({ onClick, count, score }) => {
const newScore = score + 10
const newCount = count + 1
return (
<button onClick={() => onClick(newScore, newCount)}>Score</button>
)
}
关于javascript - 跨组件发送多个 Prop React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58038722/