javascript - 跨组件发送多个 Prop React

标签 javascript reactjs components react-props react-state

我正在尝试将两个变量从组件“游戏”发送到组件“应用程序”,但我不确定如何一次发送多个 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/

相关文章:

javascript - 每次加载内容后 Ajax 调用都会递增

javascript - 如何使用 Cocos2D 制作 HTML5 Canvas 整页大小

javascript - 无法用 Jest 模拟模块并测试函数调用

javascript - 从 JS 文件调用组件函数

apache-flex - 在 Flex 4 中居中内容

javascript - Bluebird promise 过滤器。为什么是数组?

javascript - 我收到错误消息 "TypeError: callback is not a function"

reactjs - 当 Redux 状态更改为低于第一级别时,React 不会更新

javascript - 如何在 React 中使用多个表单字段自动保存?

php - cakephp 使用组件作为 Controller 方法