Отправить несколько реквизита между компонентами React - PullRequest
2 голосов
/ 21 сентября 2019

Я пытаюсь отправить две переменные из Компонента «Игра» в Компонент «Приложение», но я не уверен, как отправлять более одного реквизита одновременно.

Это то, что у меня есть:

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

С этим я могу отправить реквизит "Score" из "Game" в "App", но мне было интересноесли бы было возможно отправить больше, чем одну опору, такую ​​как «счет» и новую переменную «счет», одним и тем же нажатием кнопки, чтобы в конечном итоге иметь возможность отображать как «счет», так и «счет» в «счете»'Компенет.

Спасибо.

Ответы [ 2 ]

3 голосов
/ 21 сентября 2019

Конечно, вы можете просто обновить функцию, которую вы определили в компоненте Родительского приложения, чтобы принять два аргумента.

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>
   )
}
1 голос
/ 21 сентября 2019

Вы можете определенно отправлять более одного реквизита одновременно.Вот пример, который вы описали:

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

А в вашем компоненте Score:

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