0
export default class player extends React.Component {
constructor(...args) {
super(...args);
this.state = {
  shoot: 0
};
}

shootis the variable i'm trying to change in the function shooter, and display later in <h1>.

shooter() {
this.setState({ shoot: Math.floor(Math.random() * Math.floor(3)) });
console.log("hello");
}

render() {
return (
  <div>
    <h1>{this.state.shoot}</h1>
    <button onClick={() => this.shooter}>shoot it</button>
  </div>
);
}
} 

the <h1> is not changing as the state changes, won't the state change as shooter() fires? and doesn't it update the <h1>.

any help much appreciated. :-)

2 Answers2

2

Change the line

<button onClick={() => this.shooter}>shoot it</button>

To

<button onClick={() => this.shooter()}>shoot it</button>
v1r00z
  • 103
  • 5
0

Bind your class method shooter in your constructor, in order to use it like this onClick={this.shooter}.

You can find a further explanation here.

 export default class player extends React.Component {
      constructor(...args) {
        super(...args);
        this.state = {
          shoot: 0
        };
        this.shooter = this.shooter.bind(this);
      }

      render() {
        return (
            <div>
                <h1>{this.state.shoot}</h1>
                <button onClick={this.shooter}>shoot it</button>
            </div>
        );
      }
    }
dmraptis
  • 909
  • 1
  • 10
  • 22