通过点击游戏学习反应,onClick 不会触发。我想我只是在传递一个 * 称为 * onClick 的道具

Learning react with a click game, onClick won't fire. I think I'm just passing a prop *called* onClick

Bit组件应该是我的可点击的,由于我在Mine组件中的mine功能,它应该会增加状态。

  function Bit(props) {
        return (
    <img src={logo} className="App-logo" alt="logo" onClick={props.onClick} />
  )
}
class Mine extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      bitCoins: 0,
      clickBonus: 1,
      cps: 1,
    }
  }
  mine() {
    alert('here')
    this.setState({
      bitCoins: this.state.bitCoins + 1
    })
    console.log(this.state.bitCoins);
  }
  render() {
    let status;
    status = this.state.bitCoins
    return (
          <div>
            <Bit onClick={() => this.mine()} />
          </div>
          <div className="text-primary">{status}</div>
    )
  }
}

在 React 中从 render 返回的内容不能在顶层有兄弟元素。因此,只需用 <React.Fragment>(或 div 或您选择的任何其他内容)包装您返回的内容即可修复它。

另请注意 setState 是异步的,因此当您 console.log 立即调用它时,您可能无法获得最新的值。

class Mine extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      bitCoins: 0,
      clickBonus: 1,
      cps: 1,
    }
  }
  
  mine() {
    alert('here')
    this.setState({
      bitCoins: this.state.bitCoins + 1
    })
    console.log(this.state.bitCoins);
  }
  
  render() {
    let status;
    status = this.state.bitCoins
    return (
      <React.Fragment>
        <div>
          <button onClick={() => this.mine()}>Mine</button>
        </div>
        <div className="text-primary">{status}</div>
      </React.Fragment>
    )
  }
}

ReactDOM.render(
  <Mine />,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>