2016-01-01 109 views
2

我有一個選項頁面組件。該組件由行組成。每一行都是一個設置。該設置可以是選擇,檢查,收音機或自定義元素。該組件以兩種方式更新:組件級別onChange事件?

  1. AJAX告訴它的setState更新 - 這的setState我歸類不作爲組分的onChange只是組件更新
  2. 用戶操作行,觸發選擇/收音機/檢查的onChange觸發的的onChange觸發最頂端組件上的setState - 這個的setState我歸類爲組件的onChange

在#2開始,這意味着用戶操縱的成分,我想在最上面的組件的onChange火。有這樣的事件嗎?我似乎無法在組件生命週期中找到它。

爲什麼我不能使用componentDidUpdate的原因是因爲當用戶觸發onChange行時,我需要使用新的信息向服務器發出請求。如果AJAX告訴compoent更新,onComponentDidUpdate將會觸發,但我不需要發出AJAX請求。

+1

Donn't確切地知道你想要什麼。不能將來自父組件的'onChange'傳遞給具有道具的行解決你的問題?請問最頂級組件的onChange是什麼意思?你是指事件代表團嗎? –

+0

謝謝@張超快速回復。基本上,我想知道最頂級組件觸發的'componentDidUpdate'是否由用戶操作的setState或來自AJAX setState引起的。 – Noitidart

+1

當用戶操作導致'onChange'時,你需要觸發'setState',然後在'componentDidUpdate'中發出請求,對嗎?你爲什麼不在'onChange'中發出這個請求,並在得到這個請求的響應時觸發'setState'?我認爲這是一種更常見的做這種事情的方法,並且你不必在'componentDidUpdate'中區分ajax方式和用戶方式。 –

回答

3

您可以通過在其子組件屬性上傳遞來自Top Component的回調來完成此操作。這個回調將通過使用this.props.callbackName()由Child組件onChange事件調用。例如

TopComponent.js

// import react (i'm using es2015) 
// but the concept is the same whether you use it or not 

import React, {Component} from 'react' 

class TopComponent extends Component { 

    // the callback 
    onChildComponentChange(){ 
     doAjax().then(function(data){ 
     this.setState({foo: data}) 
     }) 

    } 

    render(){ 
     return (<ChildComponent onPropertyChange={this.onChildComponentChange}) /> 
    } 
} 

ChildComponent.js

import React, {Component} from 'react' 

class ChildComponent extends Component { 

    onChangeHandler(){ 
    // from this handler we call the top component callback 
    this.props.onPropertyChange(data) // the name of props we pass from top component 
    } 
    render(){ 
    return (<RowComponent onClick={this.onChangeHandler}/>) 
    } 
} 
+0

啊,這只是一個很好的想法,非常感謝!我也從這篇文章中學習了一些es2015,謝謝! – Noitidart

+0

是否有可能將回調函數命名爲'onPropertyChange'' onChange'?我想,爲了保持一致性,但是,我會壓倒重要的東西嗎?謝謝 – Throoze