I'm starting in ReactJS and I'm doing a score system for my game in React.
I used a component called Score to manage it.
I did a score value in the state that can be incremented by increment().
The problem is that I would like to use this function from my App component (it's an example, I created incrementScore() to show it).
However my increment() can't gain access to this.setState() when the function is called from another component.
Note that I created a button "Increment" inside Score.js which uses increment() and it's works perfectly.
Have you a solution or could you just give a clue? Thanks!
App.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
Score.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
incrementmethod there, and pass it down to the child component as a prop. There is good example of this in the official React docs: reactjs.org/docs/lifting-state-up.htmlApp, as here. So given any 2 components you can always find a common ancestor (usually below the level ofAppitself) which you can lift the state to.