无法在<h1>

时间:2019-01-06 20:35:16

标签: reactjs jsx

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

shoot是我要在功能选择器中更改的变量,稍后在<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>
);
}
} 

<h1>不会随着状态的改变而变化,不会因为shooter()的触发而改变状态?并且不会更新<h1>

非常感谢您的帮助。 :-)

2 个答案:

答案 0 :(得分:2)

更改行

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

收件人

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

答案 1 :(得分:0)

在您的构造函数中绑定类方法shooter,以便像这样onClick={this.shooter}那样使用它。

您可以找到进一步的解释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>
        );
      }
    }