簡體   English   中英

跨組件發送多個道具 React

[英]Send multiple props across components React

我正在嘗試將兩個變量從組件“游戲”發送到組件“應用程序”,但我不確定如何一次發送多個道具。

這就是我所擁有的:

//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>
        )
    }
}

有了這個,我可以將道具“分數”從“游戲”發送到“應用程序”,但我想知道是否可以發送更多道具,而不是僅發送一個道具,例如“分數”和新變量“計數”按下相同的按鈕,最終能夠在“分數”組件中同時顯示“分數”和“計數”。

謝謝。

當然可以,只需更新您在父應用程序組件中定義的 function 以接受兩個 arguments。

應用程序.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 //重構,因為它不需要使用 state

const Game = ({ onClick, count, score }) => {
   const newScore = score + 10
   const newCount = count + 1
   return (
       <button onClick={() => onClick(newScore, newCount)}>Score</button>
   )
}

您絕對可以一次發送多個道具。 這是您描述的示例:

<Score
    score={this.state.score}
    count={this.state.count}
/>

在您的分數組件中:

class Score extends Component {


    render() {

        const score = this.props.score;
        const count = this.props.count;

        return(
            <div>
                <h1>Score: {score}</h1>
                <h1>Count: {count}</h1>
            </div>
        )
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM