首页 > 解决方案 > 反应:在从另一个组件调用的函数中使用 setState?

问题描述

我从 ReactJS 开始,我正在为我的 React 游戏做一个评分系统。

我使用了一个名为 Score 的组件来管理它。

我在状态下做了一个分值,可以递增increment().

问题是我想从我的 App 组件中使用这个函数(这是一个例子,我创建它是incrementScore()为了展示它)。

但是,我increment()无法访问this.setState()从另一个组件调用该函数的时间。

请注意,我在Score.js其中创建了一个“增量”按钮increment(),它可以完美地工作。

您有解决方案还是可以提供线索?谢谢!

应用程序.js:

import Score from './Score'

class App extends React.Component {

  incrementScore() {
    Score.prototype.increment()
  }

  render() {
    return (
        <div>
          <h1 id="title">Game</h1>
          <Score />
          <Canvas /> {/*Not important here, just for the game*/}
        </div>
    )
  }
}

export default App

分数.js:

import React from 'react'

class Score extends React.Component {

  constructor() {
    super()
    this.state = {
      score: 0
    }
    this.increment = this.increment.bind(this)
  }

  increment() {
    this.setState({
      score: this.state.score + 1 //this.state.score + 1
    })
  }

  render() {
    return (
      <div>
        <p id="score">Score: {this.state.score}</p>
        <button>Incrementer</button>
      </div>
    )
  }
}

export default

标签: javascriptreactjsfunctionsetstate

解决方案


正如 Robin 所说,只需将您的状态移动到您的父App组件,并让您的Score组件成为“无状态”组件。此外,请确保将增量函数作为道具向下传递,并在按钮中将其用作onClick函数。

class App extends React.Component {
constructor() {
    super()
    this.state = {
      score: 0
    }
    this.increment = this.increment.bind(this)
  }

  increment() {
    this.setState({
      score: this.state.score + 1 //this.state.score + 1
    })
  }

  render() {
    return (
      <div>
        <h1 id="title">Game</h1>
        <Score scoreCount={this.state.score} increment={this.increment}/>
      </div>
    )
  }
}
const Score = props =>
      <div>
        <p id="score">Score: {props.scoreCount}</p>
        <button onClick={props.increment}>Incrementer</button>
      </div>

在此处查看实时示例:https ://codesandbox.io/s/wq4kqqz0mw


推荐阅读