reactjs - 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'));
解决方案
您忘记在 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>
);
}
}
那应该工作!
推荐阅读
- css - 当 textarea 有值时更改标签颜色
- php - 使用时间计算变量
- sql - 如何将 NTILE 函数应用于 SQL 列
- ssl - Logstash 不接受自签名证书并引发 sslv3 警报握手失败
- java - 如何在java中的spring数据聚合中实现$size
- php - WordPress:将查询字符串附加到所有 URL
- string - 如何创建任意长度的字符串
- kotlin - Kotlin - 我如何设置共享偏好代码以便我打开关闭的应用程序,它会打开我离开的最后一个活动
- typescript - 为什么可以将 'any' 分配给任何类型而不先显式转换它?
- php - 将 PhoneNumber 字段作为数组传递