function关键字在基于类的组件和inChange事件中



谁能帮我了解一下下面的代码片段是否有任何问题:

import React, { Component } from "react";

class AddContactForm extends Component {
constructor() {
super();
this.state = {
name: "",
email: "",
number: ""
}
}
handleOnChange(event) {
console.log("Hi");
console.log(event.target.id);
console.log(event.target.value);
}
render() {
return (
<React.Fragment>
<div className="mx-auto">
<div class="mb-3 row">
<label for="username" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="username" onChange={this.handleOnChange.bind(this)}/>
</div>
</div>
<div class="mb-3 row">
<label for="mobileNumber" class="col-sm-2 col-form-label">Mobile Number</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="mobileNumber" onChange={this.handleOnChange}/>
</div>
</div>
<div class="mb-3 row">
<label for="emailId" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="emailId" onChange={this.handleOnChange}/>
</div>
</div>
<button className="btn btn-primary w-25">Add</button>
</div>
</React.Fragment>
)
}
}
export default AddContactForm;

我面临的问题如下:

1 -无法对handleOnChange方法使用function关键字

2 -我的输入都没有触发onChange事件。我无法在控制台中获得HandleOnChange方法中添加的任何日志。

谢谢。

在构造函数中绑定所有的方法。

constructor() {
super();
this.state = {
name: "",
email: "",
number: ""
}
this.handleOnChange: this.handleOnChange.bind(this)
}

在你的输入中像这样使用<input onClick={this.handleOnChange} />

除了@Muhammad指出的错误之外,您的代码中几乎没有错误,为了避免jsx的冲突,更改了一些属性名称,因此:

  1. class变为className
  2. for变成了htmlFor,这里也有类似的问题。

还值得注意的是,使用箭头函数比使用bind更受欢迎,因此您通常将该函数创建为箭头函数。

handleOnChange = (event) => {
console.log("Hi");
console.log(event.target.id);
console.log(event.target.value);  
};

并让onChange调用它

onChange={this.handleOnChange}

你可以参考这个代码盒的演示,你也可以在这里阅读这两个问题:

  1. correct-use-of-arrow-functions-in-react
  2. how-to-avoid-bind-or-inline-arrow-functions-inside-render-method

最新更新