简体   繁体   English

触发onBlur时e.target()未定义

[英]On firing onBlur e.target() is undefined

In my react application, the following script is executed when onBlur is fired. 在我的react应用程序中,触发onBlur时执行以下脚本。 But e.target is returning null. 但是e.target返回null。 So I'm unable to retrieve the text entered to validate. 因此,我无法检索输入的文本进行验证。

handleNameValidation({ target }) {
    console.log("The target is : ", target);
}

But, I have a similar script working fine when firing an onChange event. 但是,当触发onChange事件时,我有一个类似的脚本可以正常工作。 Is this an expected behavior or how can I access the value when onBlur is fired. 这是预期的行为还是触发onBlur时如何访问该值。

Any pointers would be helpful. 任何指针都会有所帮助。

Thanks and Regards, San 感谢和问候,San

It looks like you have lost context of the handler: 看来您失去了处理程序的上下文:

1) use class property fields 1)使用类属性字段

handleNameValidation = ({ target }) => {
    console.log("The target is : ", target);
}

2) bind context in contructor 2)在contructor中绑定上下文

construtctor(props){
  super(props);

  this.handleNameValidation = this.handleNameValidation.bind(this);
}

handleNameValidation({ target }) {
    console.log("The target is : ", target);
}

Here is a working example: 这是一个工作示例:

https://codesandbox.io/s/18kyz9v264 https://codesandbox.io/s/18kyz9v264

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

class App extends React.Component {
  render() {
    return <div>
      <input onBlur={this.onBlur} />
    </div>;
  }

  onBlur = (e) => {
    console.log(e.target);
  }
}

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

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

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