リアクトコンポーネントへのコールバックを通過さの差

ドリューCortright:

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;

この例では、私は私が成功した2つの方法で部品の小道具にこれを渡すことができる取り扱いとのこぎりだというのonClickイベントを持っています。私は、彼らが同じように関数に現れるので、正確に差が両方の方法であると思いまして。なぜ両方の方法が動作していますか?

keikai :

それは奇妙なようだ共通点です。

文書で詳細を参照してくださいハンドリング、イベント

// 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、あなたのコンストラクタで、そうでない場合、あなたは、次の2つのメソッドを使用することもできます。

A.パブリッククラスフィールドの構文

ここではデフォルトで有効になって作成するには、アプリに反応

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
/>

サンプル

基本的に私たちの練習では、私たちが使用するパブリッククラスのフィールドの構文以下のようになりますのparamsとし:

// 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、それに異なるのparamsを渡すことによって。

// 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

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=32462&siteId=1