簡體   English   中英

處理多個組件實例的回調

[英]Handling callbacks for multiple component instances

剛開始使用 React,試圖替換一個功能強大但非常復雜的 jQuery 頁面。 我正在承擔這項任務,因為我需要添加額外的功能,繼續使用 jQuery 的糾結網絡將變得站不住腳。

此頁面是一種排序形式,包含多個目的地和與目的地相關的任務。 我讀到的有關 React 的所有內容都告訴我將狀態保持在最高包含級別,本質上是我的 OrderCreation/App 級別 - 對嗎?

所以,現在我有一個 DestinationInput 組件,它通過 mixin 處理 GoogleAutocomplete 並具有可切換的編輯狀態(在選擇自動完成位置后,它變成一對 h4/h6 節點 - 單擊此將交換回輸入字段)。

我在同一個應用程序中有幾個這樣的 DestinationInput 組件——我不希望每個 DestinationInput 組件實例有 1 個 destinationUpdated 回調——特別是因為這將成為一個動態數量的實例加班。

我認為正確的方法是將通用回調方法 prop 傳遞給子級,並讓子級將標識符和新值傳遞給父級。 我使用鑰匙嗎? 參考? 我真的沒有看到任何關於如何處理更新父狀態的多個子實例的最佳實踐。

我在想什么應該有效

var OrderCreate = React.createClass({
   getIntitialState = function () {
      return {
         destinations: []
      }
   },

   updateDestination = function(id, place) {
      this.setState(destinations[id], place);
   },

   render = function() {
      return (
         for (var i=0; i < this.state.destinations.length; i++) {
            <DestinationInput key={ i }
                              place={this.state.destinations[i]} 
                              onChange={this.updateLocation} />
         };
      );
   }
});

var DestinationInput = React.createClass({
   mixins = [GoogleAutocompleteMixin],
   getIntitialState = function () {
      return {
         text: this.props.text
      };
   },

   getDefaultProps = function() {
      return {
          text: ""
      };
   },

   handleChange = function(event) {
       this.setState({text: event.target.value });
   },

   placeSelected = function(place) {
      this.props.onChange(this.props.key, place);
   },

   render = function() {
      return (
          <input onChange={ this.handleChange } value={ this.state.text } />
      );
   }
});

Flux 是一種用於在內存中實現數據存儲的客戶端方法,因此它與服務器上發生的任何事情完全無關。

我不確定您到底在追求什么,但我認為您只是在問將函數傳遞給孩子是否是一個好主意。 是的,非常好。

為簡潔起見,我嘗試只包含重要的函數傳遞內容。

class Button extends React.Component {
  onClick() {
    this.props.onClick( this.props.id )
  }

  render() {
    return <Button onClick={ this.onClick.bind( this ) }>Click me</button>
  }
}

class Parent extends React.Component {
  onDoStuff( stuff ) {
    console.log( stuff ) // comes from each button
  }

  render() {
    return (
      <div>
        <Button id="number1" onClick={ this.onDoStuff } />
        <Button id="number2" onClick={ this.onDoStuff } />
      </div>
    }
  }
}

Parent.onDoStuff被傳遞給Button組件,其中一個處理程序最終將附加到 DOM 節點,該節點將解析為調用onDoStuff ( this.props.onClick ) 並將相關數據傳回父組件。 從那里你可以決定你需要用它做什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM