繁体   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