首页 > 解决方案 > onClick 事件未在简单代码上触发(ReactJS)

问题描述

对于事件侦听器没有触发的原因有点困惑。我也尝试不注释掉绑定,因为我认为没有必要,但它仍然不起作用。不知道这里的错误是什么......

我还检查了最后一行(在我的主 html 标记上的 id=root 处渲染 App 组件......这很好)。

import React, { Component } from 'react';
import { render } from 'react-dom';

class App extends React.Component {
  constructor() {
    super();
    this.state = {text: 'X'};
    this.i = 0;
    this.val = ['X', 'O'];
    this.update = this.update.bind(this);
  }

  //click to change state from X to O.
  update() {
    console.log("clicked");
    // if(this.i === 0) {
    //   this.setState({text: this.val[1]});
    //   this.i = this.i + 1;
    // } else {
    //   this.setState({text: this.val[0]});
    //   this.i = this.i - 1;
    // }
  }

  render() {
    return (
      <div>
        <h1>Tic Tac Toe</h1>
        <Box text={this.state.text} onClick={this.update}/>
      </div>
    );
  }
}

class Box extends React.Component {
  render() {
    return (
      <button className = "box" >{this.props.text}</button>
      // <button className = "box">hi</button>
    );
  }
}

render(<App />, document.querySelector('#root'));

标签: reactjs

解决方案


您忘记在 Box 上使用传递的 onClick 道具。

class Box extends React.Component {
  render() {
    return (
      <button className="box" onClick={this.props.onClick}>{this.props.text}</button>
      // <button className="box">hi</button>
    );
  }
}

那应该工作!


推荐阅读