绑定到click事件时这是什么

时间:2018-03-25 17:54:30

标签: reactjs binding onclick

我有以下反应脚本(index.js& app.js)。我对三个问题感到困惑:

在index.js脚本中,为什么{count ++}没有递增而{count = count + 1}是?我以为他们是一回事。

在app.js脚本中,我对这涉及的内容感到困惑:

<button onClick={this.addOne.bind(this)}>increment</button>

我认为第一个引用了App并获得了addOne方法,其中bind(this)引用了click事件。注意下面的render()我有var self = this。如果我在按钮语句中用self替换其中一个或两个,它仍然有效。那么bind(this)究竟在做什么呢?

不确定但答案是答案,因为我们在渲染函数中调用它,这是指App。第一个这个让我们得到方法addOne,然后我们将这个(App)绑定到这个函数addOne,这样我们就可以访问props和state了吗?

如果上面的答案在右边,我的第三个问题是为什么我不能将addOne函数更改为参数,然后在onClick事件中使用:

<button onClick={this.addOne(this)}>increment</button>

/* index.js */
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
var count = 4
ReactDOM.render(<App count={count++}/>, document.getElementById('root'));
registerServiceWorker();


/*app.js */
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
   constructor(props){
     super(props)
     this.state={increment:this.props.count}

   }

   addOne(){
      this.setState({increment: this.state.increment+1})
   }

  render() {
  var  self=this
    return (

    <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>


        <p>{this.state.increment}</p>

        <button onClick={this.addOne.bind(this)}>increment</button>
      </div>
    );

  }

}

export default App;

1 个答案:

答案 0 :(得分:2)

在javascript函数中是一等公民,我们可以像普通变量一样传递函数。例如:onClick={this.addOne} 在这里,我们将addOne函数作为参数传递给onClick事件,指示它onclick of element invoke the function passed

唯一的问题是你的addOne函数实现包含对this(this.setState)的引用。

如果您通过在func a.func()中说this来引用a来调用某个方法(此处func绑定到a)。但是,如果您只是调用func(),则func()this中的内容将是未定义的。为避免这种情况,您可以明确地将func绑定到this

例如:a.func()func.bind(a)()相同 现在,func中对this的引用将指向a

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

this指的是类的一个实例(它是App对象。)

why is {count++} not incrementing whereas {count=count+1} is? I thought they were the same thing.这是因为count ++只有在当前语句中使用count后才会增加count的值。而++ count或count + 1将在当前语句本身中递增它。

如果你想将self作为变量传递给addOne函数,你的addOne应该是这样的。

addOne(self){
 return function() { 
   self.setState({increment: self.state.increment+1})
 }
}