2015-10-30 27 views
1

簡單響應狀態示例。父組件是應用程序,剛開始時只顯示一個按鈕,當點擊按鈕時,它應該呈現AllRecipes(這個工作,我能夠管理AllRecipes的狀態)。 AllRecipes內部是一個按鈕,需要觸發狀態更改才能進一步呈現ingredients(此按鈕在單擊時不執行任何操作,它需要切換配料狀態)。我覺得這是一個如何管理國家一個非常好的小例子,但我失去了一些東西..子組件不能觸發狀態變化

var App = React.createClass({ 

    getInitialState: function(){ 
     return {showIngredients: false, showRecipes: false}; 
    }, 

    toggleRecipes: function(){ 
     this.setState({showRecipes: !this.state.showRecipes}) 
    }, 

    toggleIngredients: function(){ 
     this.setState({showRecipes: !this.state.showRecipes}) 
    }, 

    render: function() { 
     var recipes = this.state.showRecipes ? <Recipes/> : null; 
     return (
       <div> 
        <h1> Recipe App </h1> 
         <button onClick={this.toggleRecipes}> Show Recipes </button> 

         {recipes} 
       </div> 
      ); 
    } 
}); 

var Recipes = React.createClass({ 
    render: function() { 
     var ingredients = this.props.showIngredients ? <Ingredients/> : null; 
     return (
       <div> 
        <h1> list of recipes </h1> 
         <ul> 
          <li> Chicken Soup </li> 
          <li> Chicken Wings </li> 
          <button onClick={this.props.toggleIngredients}> Show Recipes </button> 
          {ingredients} 
         </ul> 
       </div> 

      ); 
    } 
}); 

var Ingredients = React.createClass({ 
    render: function() { 
     return (
       <div> 
        <h1> List of Ingredients </h1> 
         <ul> 
          <li> Salt </li> 
          <li> Pepper </li> 
         </ul> 
       </div> 
      ); 
    } 
}); 

React.render(<App/>, document.body); 
+0

本質的配方成分根本無法看到app'父組件'的toggleIngredients功能。我錯誤地設計了流程,還是錯過了一些小的東西? – fresh5447

回答

1

它看起來像你不及格toggleIngredientsRecipes。嘗試改變

var recipes = this.state.showRecipes ? <Recipes/> : null; 

var recipes = this.state.showRecipes ? <Recipes toggleIngredients={this.toggleIngredients} /> : null; 
+0

是的,我認爲這絕對是我錯誤的地方!我得到這個錯誤'未捕獲的錯誤:不變的違規:預期的onClick監聽器是一個函數,而不是類型字符串'你有一個語法錯誤在您的帖子或東西? – fresh5447

+0

應該是這樣的嗎? '<食譜toggleIngredients =「{this.toggleIngredients}」/>' – fresh5447

+0

是的,這看起來是正確的(類似於我發佈的內容,但帶有正確的方法名稱 - 對不起)。 – pherris

相關問題