我正在开发一个Recipe Box项目,我有一个程序,允许用户点击一个按钮,然后显示输入框,允许用户将新配方添加到列表中。
我在表单中有两个输入。一个用于添加配方的名称,一个用于配料。配方名称的输入有效并允许用户添加名称,但第二个输入框不会更新状态中的成分。
为什么不在州内更新ingredientVal?为什么我不能在第二个输入框中输入文字?
import React, { Component } from 'react';
import RecipeList from './RecipeList';
import './App.css';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
items: ["Pumpkin Pie", "Spaghetti", "Onion Pie"],
ingredients:[
["Pumpkin Puree", "Sweetened Condensed Milk", "Eggs", "Pumpkin Pie Spice", "Pie Crust"],
["Noodles", "Tomato Sauce", "(Optional) Meatballs"],
["Onion", "Pie Crust"]
],
inputVal: '',
ingredientVal: '',
showRecipe: false
};
}
// Get text user inputs for recipe
handleChange = (event) => {
this.setState({inputVal: event.target.value});
};
handleIngredientChange = (event) => {
this.setState({ingredientVal: event.target.value});
}
// When user submits recipe this adds it
onSubmit = (event) => {
event.preventDefault()
this.setState({
inputVal: '',
items: [...this.state.items, this.state.inputVal],
ingredientVal: '',
ingredients: [...this.state.ingredients, this.state.ingredientVal]
});
}
onIngredientSubmit = (event) => {
event.preventDefault()
this.setState({
ingredientVal: '',
ingredients: [...this.state.ingredients, this.state.ingredientVal]
});
}
// Shows recipe
AddRecipe = (bool) => {
this.setState({
showRecipe: bool
});
}
render() {
return (
<div className="App">
<h3>Recipe List</h3>
<RecipeList items={this.state.items} ingredients={this.state.ingredients} />
<button onClick={this.AddRecipe}>Add New Recipe</button>
{ this.state.showRecipe ?
<div>
<form className="Recipe-List" onSubmit={this.onSubmit}>
<div className="Recipe-Item">
<label>Recipe Name</label>
<input
value={this.state.inputVal}
onChange={this.handleChange} />
</div>
<div className="Recipe-Item">
<label>Ingredients</label>
<input
value={this.state.ingredientVal}
onChange={this.state.handleIngredientChange} />
</div>
<button>Submit</button>
</form>
</div>
:null
}
</div>
);
}
}
答案 0 :(得分:2)
您this.state.handleIngredientChange
作为onChange
时应该this.handleIngredientChange