2015-04-20 110 views
0

我對React只有幾個小時的新感覺,所以我可能錯過了一些明顯的東西。我有一個應用程序,它看起來有點像這樣:如何觸發React中較高級元素的事件?

var App = React.createClass({ 
    myAction: function(thingId) { 
     this.setState({currentThing: thingId}); 
    }, 

    render: function() { 
     return (<ThingsContainer app={this}/>); 
    } 
    }); 

    var ThingsContainer = React.createClass({ 
    render: function() { 
     return (<ThingList app={this.props.app}/>); 
    } 
    }); 

    var ThingList = React.createClass({ 
    render: function() { 
     var self = this; 
     var thingNodes = this.props.data.map(function (thing) { 
     return (<Thing thing={thing} app={self.props.app} key={thing.id}></Thing>); 
     }); 
     return (<div>{thingNodes}</div>); 
    } 
    }); 

    var Thing = React.createClass({ 
    performAction: function() { 
     this.props.app.myAction(this.props.thing.id); 
    }, 

    render: function() { 
     return (
     <div> 
      <h2>{this.props.thing.title}</h2> 
      <button onClick={this.performAction}>pip!</button> 
     </div> 
    ); 
    } 
    }); 

    React.render(<App />, document.getElementById('content')); 

我想從較低級別的對象觸發頂級對象的事件。 relevant page似乎沒有直接解決這種情況。

在我的解決方案中,我將app對象傳遞給幾個級別。這感覺不對。在Ember中,我將能夠使用單身控制器。在Angular中,我可能會使用一項服務。在Backbone或jQuery中,我會使用一個事件。

我不知道這種類型的魔術佈線對React有什麼期望。

是我的上述解決方案,它涉及組件之間的明確佈線,即使在幾個邊緣,正確的方法?

回答

0

我也只是向下傳遞的功能,而不是整個對象:

var App = React.createClass({ 
    myAction: function(thingId) { 
     this.setState({currentThing: thingId}); 
    }, 

    render: function() { 
     return (<ThingsContainer myAction={this.myAction}/>); 
    } 
    }); 

    var ThingsContainer = React.createClass({ 
    render: function() { 
     return (<ThingList myAction={this.props.myAction}/>); 
    } 
    }); 

    var ThingList = React.createClass({ 
    render: function() { 
     var self = this; 
     var thingNodes = this.props.data.map(function (thing) { 
     return (<Thing thing={thing} myAction={this.props.myAction} key={thing.id}></Thing>); 
     }); 
     return (<div>{thingNodes}</div>); 
    } 
    }); 

    var Thing = React.createClass({ 
    performAction: function() { 
     this.props.myAction(this.props.thing.id); 
    }, 

    render: function() { 
     return (
     <div> 
      <h2>{this.props.thing.title}</h2> 
      <button onClick={this.performAction}>pip!</button> 
     </div> 
    ); 
    } 
    }); 

    React.render(<App />, document.getElementById('content')); 

比我看不出有什麼毛病你的方法等,但它確實覺得有點奇怪在第一,但這種做法的好處關於它的父元素總是負責直接修改狀態,並且調試這樣的問題非常容易,因爲有一個非常清晰簡潔的「流程」。

相關問題