簡單響應狀態示例。父組件是應用程序,剛開始時只顯示一個按鈕,當點擊按鈕時,它應該呈現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);
本質的配方成分根本無法看到app'父組件'的toggleIngredients功能。我錯誤地設計了流程,還是錯過了一些小的東西? – fresh5447