2016-01-12 71 views
0

我正在使用沒有通量的反應軌道。通過父對象本身作爲兒童的道具

我意識到我在我的父組件jsx文件中定義了太多的函數,所以我想重構它並在另一個文件中定義函數。

# application.js 
//= require_self 
//= require react 
//= require react_ujs 
//= require components 
//= require_tree . 
window.myApp = {} 

# custom.js 
myApp.sayLol = function(parentComponent) { 
    alert("LOL"); 
    parentComponent.setState({something: 'something'}); 
} 

# parent_component.js.jsx 
var ParentComponent = React.createClass({ 
    // sayLol: function(){ 
    // alert("LOL"); 
    // this.setState({something: 'something'}); 
    // }, 
    render: function(){ 
    // return (<ChildComponent sayLol={this.sayLol} />); 
    return (<ChildComponent parentComponent={this} />); 
    } 
}) 

# child_component.js.jsx 
var ChildComponent = React.createClass({ 
    handleClick: function(){ 
    myApp.sayLol(this.props.parentComponent); 
    }, 
    render: function(){ 
    return (<div onClick={this.handleClick}>say LOL</div>) 
    } 
}) 

所以我所做的就是定義的功能,即sayLol(),該成分會在一個單獨的custom.js文件來調用。

教程的方式是將父組件內部的函數定義爲本地函數,通常作爲道具傳遞給子項,如parent_component.js.jsx中的註釋所示。

我還傳遞父對象,以便我可以使用custom.js中定義的解耦函數來執行某些操作,例如將父對象的狀態從子組件中更改。

它目前正在處理我的應用程序,但我不確定是否將父對象本身作爲整體傳遞是件好事。愛聽到任何建議:)在此先感謝。

回答

1

Nah。傳遞整個父對象可能不是想要的。這是因爲子對象必須對父內部有太多的知識。這最終會產生額外的難度來測試意大利麪代碼。

取而代之的是傳遞特定的回調作爲道具。這些回調不一定需要來自父組件的方法,但這通常會使它們更容易測試。

如果你有大量的回調,將它們分組到一個單獨的對象中,這些對象可以作爲道具傳遞,但大多數應用只是明確地傳遞單個回調。