小编典典

React组件回调实现方法之间有什么区别

reactjs

import React from 'react';

import ChildComponent from './ChildComponent';



class SampleComponent extends React.Component {



  sampleCallbackOne = () => {

    // does something

  };



  sampleCallbackTwo = () => {

    // does something

  };



  render() {

    return (

      <div>

          <ChildComponent

            propOne={this.sampleCallbackOne}

            propTwo={() => this.sampleCallbackTwo()}

          />

      </div>

    );

  }

}



export default SampleComponent;

在此示例中,我正在处理一个onClick事件,并看到可以通过两种方式将其成功传递给组件的props。

我想知道两种方式的确切区别是什么,因为它们似乎以相同的方式起作用?

为什么两种方法都起作用?


阅读 256

收藏
2020-07-22

共1个答案

小编典典

这是一个很奇怪的共同点。

请参阅处理事件文档中的详细信息

// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);

handleClick() {
  console.log('this is:', this);
}

<button onClick={this.handleClick}>

如果不加()身后this.handleClick,你需要绑定this在你的构造,否则,您可能希望使用接下来的两个方法:

A.公共类字段的语法

Create React App中默认启用

handleClick = () => {
  console.log('this is:', this);
}

<button onClick={this.handleClick}>

B.箭头功能

可能会导致性能问题,建议不要使用,请参阅上面的文档。

// The same on event handling but different in:
<button
  onClick={(e) => this.deleteRow(id, e)} // automatically forwarded, implicitly
/>
<button
  onClick={this.deleteRow.bind(this, id)} // explicitly
/>

样品

基本上在我们的实践中,我们使用带有参数的 公共类字段语法 ,如下所示:

// No need to bind `this` in constructor
// Receiving params passed by elements as well as getting events of it
handler = (value: ValueType) => (event: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement>) => {
  // Do something with passed `value` and acquired `event`
}
<NumberFormat
  ...
  onBlur={this.handler(someValue)} // Passing necessary params here
/>

我们可以handler function通过传递不同的参数来共享它们。

// Justify via keyword of stored content in flat data structure
handler = (value: string) => (event: React.ChangeEvent<HTMLInputElement>, id: ValidationItems) => {
  // Do something with 
  // passed `value`, 
  // acquired `event`,
  // for each element diffenced via `id`
};

<YourComponent
  id="ID_1"
  value={store.name1}
  onChange={this.handler("name1")}
/>;

<YourComponent
  id="ID_2"
  value={store.name2}
  onChange={this.handler("name2")}
/>;

// ... more similar input text fields
2020-07-22