简体   繁体   English

ReactJS:onChange 事件未触发输入

[英]ReactJS: onChange event is not firing input

Here's the code这是代码

import React, { Component, useImperativeHandle } from 'react';

class SearchBar extends Component {
render() {
return <input onChange={this.onInputChange} />;
}
onInputChange(event) {
  console.log(event)
 }
}

export default SearchBar;

There's no error still on input nothing get the console logged.输入时仍然没有错误,没有记录控制台。

Screenshot of input and console输入和控制台截图

You need to bind your event handler to your class component as below您需要将您的事件处理程序绑定到您的 class 组件,如下所示

 import React, { Component, useImperativeHandle } from 'react';

 class SearchBar extends Component {
   constructor(props) {
     super(props);
     this.onInputChange = this.onInputChangebind(this); //You NEEDED THIS
  }
   
  render() {
    return <input onChange={this.onInputChange} />;
  }
  onInputChange(event) {
    console.log(event)
  }
  }

export default SearchBar;

As in the screenshot you have selected the errors.如屏幕截图所示,您选择了错误。 Click on the 10 messages (on the left side of the screenshot) and you will see the console output.单击10 messages (在屏幕截图的左侧),您将看到控制台 output。

Works on my side... i highlighted the console.log outputs as shown on picture在我这边工作......我突出显示了console.log输出,如图所示在此处输入图像描述

otherwise if you needed to see the words you typed on the input tag you can just do console.log(event.target.value) instead of console.log(event)否则,如果您需要查看在输入标签上键入的单词,您可以执行console.log(event.target.value) instead of console.log(event)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM