javascript 反应:这在事件处理程序中为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33631482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:43:11  来源:igfitidea点击:

React: this is null in event handler

javascriptreactjsthis

提问by Midiparse

I have a LoginForm component. I want to check before submit, that both loginNameand passwordis set. I tried with this code (a lot of stuff omitted):

我有一个 LoginForm 组件。我想在提交之前检查,这两个loginNamepassword设置。我试过这段代码(省略了很多东西):

class LoginForm extends Component {

  constructor() {
    super();

    this.state = {
      error: "",

      loginName: "",
      password: "",
      remember: true
    };
  }


  submit(e) {
    e.preventDefault();
    if(!this.state.loginName || !this.state.password) { //this is null
      this.setState({ error: "Fill in both fields" });
    } else {
      console.log("submitting form");
    }
  }

  render() {
    return (
      <div className="col-xs-12 col-sm-6 col-md-4">
        <form className="login" onSubmit={this.submit}>
          <button type="submit" className="btn btn-default">Sign in</button>
        </form>
      </div>
    );
  }
}

export default LoginForm;

however, i get a TypeErrorin the event handler, saying that thisis null.

但是,我TypeError在事件处理程序中得到一个,说它this为空。

What should I be doing?

我该怎么办?

回答by Alexander T.

You need set thisfor submitmethod because now thisis undefined, for this operation you can use .bind

您需要 set thisforsubmit方法,因为现在thisundefined,对于此操作,您可以使用.bind

onSubmit={ this.submit.bind(this) }

Example

Example

or you can use arrow function

或者你可以使用箭头功能

onSubmit={ (e) => this.submit(e) }

Example

Example

回答by huston007

React was binding callbacks to this for you before. But now it is gone, and you have to bind it yourself or make wrapper like

React 之前为你绑定了回调函数。但现在它不见了,你必须自己绑定它或制作像这样的包装纸

onSubmit={() => this.submit()}

回答by Oleg

For those who is using Babel, you can use bind operatorwith transform-function-bindplugin:

对于那些使用 Babel 的人,你可以使用带有transform-function-bind插件的绑定运算符

onSubmit={::this.submit}

which is a syntactic sugar for:

这是一个语法糖:

onSubmit={this.submit.bind(this)}

回答by Vennesa

You have not bound the thisto your class; You can use ES6 class properties feature to get around the problem in the cleanest way; So all you need to do is:

你还没有绑定this到你的类;您可以使用 ES6 类属性功能以最干净的方式解决问题;所以你需要做的就是:

   submit = (e) => {
      // some code here
   }

The arrow function will auto bind it; Much nicer than binding it in a constructor; the most important thing is never ever do it this way:

箭头函数会自动绑定它;比在构造函数中绑定要好得多;最重要的是永远不要这样做:

onSubmit={() => this.submit()}

This will create a function which is an object in javascript and it will take some memory and is now residing inside your redner function! which makes it so expensive. renderfunction is part of the code that runs so many times and each time your submitfunction is also created and you will end up with some performance relates issues. So your code should be like:

这将创建一个函数,它是 javascript 中的一个对象,它将占用一些内存,现在驻留在您的 redner 函数中!这使它如此昂贵。render函数是运行了很多次的代码的一部分,每次你的submit函数也被创建,你最终会遇到一些与性能相关的问题。所以你的代码应该是这样的:

class LoginForm extends Component {
  submit = (e) => {
    // some code here
  }

  render() {
    return (
        <form className="login" onSubmit={ this.submit }>
          <button type="submit" className="btn btn-default">Sign in</button>
        </form>
      );
    }
}

export default LoginForm;

Here you will not have the performance issue, also you will not have the binding issue and your code looks much nicer.

在这里你不会有性能问题,也不会有绑定问题,你的代码看起来更好。