在React.js中,为什么我们不必传递参数事件处理函数?

时间:2019-09-19 18:51:00

标签: javascript reactjs onclick event-handling arrow-functions

例如,在渲染的 REACT 组件中,如果我需要传递一个参数,它将看起来像这样:

<button onClick={() => this.doSomething(**passed in parameter**)}>Press me!</button>

这很好。但是,为什么不必首先将其澄清为粗箭头函数中的参数呢?像这样:

<button onClick={(**PARAMETER PASSED IN HERE FIRST**) => this.doSomething(**SAME PARAMETER PLACED HERE**)}>Press me!</button>

1 个答案:

答案 0 :(得分:1)

请参阅Scope

// (a,b) are parameters passed by `Component` to `onClick` handler.
<Component onClick={(a,b) => this.doSomething(d)}/>

// Simple class example
class App extends React.Component {

  doSomething = (a,b) => {
    console.log('a',a,'b',b);
  }

  render() {
//                    onClick={this.doSomething}
    return <Component onClick={(a,b) => this.doSomething(a,b)}/>
  }
}

class Component extends React.Component {

  coolClick = () => {
    this.props.doSomething('hello','world')
  }

  render() {
    return <button onClick={this.coolClick}>Active doSomething</button>
  }
}

// d is a parameter available in the current scope
<Component onClick={() => this.doSomething(d)}

// Simple examples of possible scopes
import { d } from './consts'

const d = 5;

class App extends React.Component {

  doSomething = (x) => {
    console.log('x',x);
  }

  render() {
    const d = 5;
    return <Component onClick={() => this.doSomething(d)}/>
  }
}