【发布时间】:2016-10-01 22:11:13
【问题描述】:
我正在尝试获取用户输入到模式输入框中的值,然后将它们添加到我的状态数组中。我试图从输入中获取值,然后将它们推送到我的状态数组的克隆中,然后将状态设置为克隆。但是,这种方法似乎不起作用。如果有人能插话,我将不胜感激。
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')
)
【问题讨论】:
标签: javascript reactjs react-jsx jsx