onClick 事件未在简单代码 (ReactJS) 上触发



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

我还三重检查了最后一行(在我的主 html 标签上的 id=root 处渲染应用程序组件......那很好(。

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'));

你忘了在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>
);
}
}

这应该有效!

最新更新