我想獲得用戶輸入到模態輸入框的值,然後將它們添加到我的狀態數組中。我嘗試從輸入中獲取值,然後將它們推入我的狀態數組的克隆中,然後將狀態設置爲克隆。但是,這種方法似乎並不奏效。我很感激,如果任何人能chime英寸爲什麼我的添加功能不起作用?
var Recipes = React.createClass({
// hook up data model
getInitialState: function() {
return {
recipeList: [
{recipe: 'Cookies', ingredients: ['Flour', 'Chocolate']},
{recipe: 'Pumpkin Pie', ingredients: ['Pumpkin Puree', 'Sweetened Condensed Milk', 'Eggs', 'Pumpkin Pie Spice', 'Pie Crust']},
{recipe: 'Onion Pie', ingredients: ['Onion', 'Pie-Crust']},
{recipe: 'Spaghetti', ingredients: ['Noodles', 'Tomato Sauce', 'Meatballs']}
]
}
},
ingredientList: function(ingredients) {
return ingredients.map((ingredient, index) => {
return (<li key={index} className="list-group-item">{ingredient}</li>)
})
},
eachRecipe: function(item, i) {
return (
<div className="panel panel-default">
<div className="panel-heading"><h3 key={i} index={i} className="panel-title">{item.recipe}</h3></div>
<div className="panel-body">
<ul className="list-group">
{this.ingredientList(item.ingredients)}
</ul>
</div>
</div>
)
},
add: function(text) {
var name = document.getElementById('name').value;
var items = document.getElementById('ingredients').value.split(",");
var arr = this.state.recipeList;
arr.push({ recipe: name, ingredients: items });
this.setState({recipeList: arr})
},
render: function() {
return (
<div>
<div>
<button type="button" className="btn btn-success btn-lg" data-toggle="modal" data-target="#myModal">Add Recipe</button>
<div id="myModal" className="modal fade" role="dialog">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal">×</button>
<h4 className="modal-title">Add a new recipe</h4>
</div>
<div className="modal-body">
<form role="form">
<div className="form-group">
<label forName="recipeItems">Recipe</label>
<input ref="userVal" type="recipe" className="form-control"
id="name" placeholder="Enter Recipe Name"/>
</div>
<div className="form-group">
<label for="ingredientItems">Ingredients</label>
<input ref="newIngredients" type="ingredients" className="form-control"
id="ingredients" placeholder="Enter Ingredients separated by commas"/>
</div>
<button onClick={this.add} type="submit" className="btn btn-default">Submit</button>
</form>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
{
this.state.recipeList.map(this.eachRecipe)
}
</div>
</div>
);
}
});
ReactDOM.render(
<Recipes />,
document.getElementById('master')
)
非常感謝你,我明白你的方法和原因。我不敢相信這是一個簡單的解決方案! – Malekaii