2017-04-02 58 views
1
class App extends Component { 
constructor(props){ 
super(props); 
this.state={ recipes :{} } 
this.addRecipe=this.addRecipe.bind(this); 
} 

addRecipe (recipe) {//add new fish to recipes 
var timestamp = (new Date()).getTime(); 
this.state.recipes['recipe'+timestamp] = recipe; 
this.setState({ recipes : this.state.recipes }); 
} 
componentWillMount(){ 
    this.setState({ 
    recipes : require('./sample-recipes') 
}); 
} 
render() { 
return (
    <div className="App"> 
    <h2>Welcome to the Recipe Book</h2> 
    <button> {/*onClick, how to call Addrecipe here.*/ } 
    Add Recipe 
    </button> 
    <AddRecipe addRecipe={this.addRecipe}/> 
    <div>{this.state.recipes}</div> 
    </div> 
); 
} 
} 

var AddRecipe = React.createClass({ 
create : function(event) { 
event.preventDefault(); 
var recipe = { 
    name : this.refs.name.value, 
    ingredients:this.refs.ingredients.value 
} 

this.props.addRecipe(recipe); 
this.refs.form.reset(); 
}, 
render : function() { 
return (
    <form className="add" ref="form" onSubmit={this.create}> 
    <span> Recipe <input type="text" ref="name" placeholder="Recipe Name"/>   

</span> 
    <span>Ingredients <input type="text" ref="ingredients"    

placeholder="ingredients" /></span>  
    <button type="submit">Add</button> 
    <button type="submit">Cancel</button> 
    </form> 
) 
    } 
    }); 
    export default App; 

我建立在reactjs本食谱书(我已经开始学习反应)。反应的组分不显示


1)如何在页面加载时从文件sample-recipes.js中显示所有配方。为什么它不会在写{this.state.recipes}时在文件中显示所有食谱。


2)如何在点击按钮(Add Recipe)时调用AddRecipe组件。

+0

我强烈建议你参考一些好教程。 – Ved

+0

是的,我正在从Wes Bos教程中学习。 –

回答

1

1)食谱应该是一个数组,你必须映射并返回html或其他组件的内部每个对象。首先,你必须当前状态的结构改变是这样的:

componentWillMount(){ 
    this.setState({ 
    recipes : [{ 
     //include timestamp here, I created example recipe to get it to work 
     name : 'Tomato', 
     ingredients:'Just Tomato' 
    }] 
    }); 
} 

然后在addRecipe功能,你必须下一个配方添加到一个数组和不能使用this.state.sth外构造

addRecipe (recipe) { 
    this.setState({ recipes: [...this.state.recipes, recipe]}); 
} 

当然,您可以按照您尝试的方式映射对象,但使用数组更容易。现在

可以显示食谱是这样的:

<ul> 
    {this.state.recipes.map(recipe => { 
    return <li>{recipe.name}</li> 
    })} 
</ul> 

2)你需要另一种状态变量,如displayAddRecipeForm东西。然后绑定这改变了状态相反的函数:

<button onClick={() => {this.setState({ displayAddRecipeForm: !this.state.displayAddRecipeForm })}}>Add Recipe</button> 

传递状态AddRecipe组件作为一个属性,设定该类立足道具:

<form className={this.props.display ? '' : 'hide'} ref="form" onSubmit={this.create}> 
+0

是的,这工作正常。我只是不明白addRecipe函数。你能解释一下吗? –

+0

和表单部分。我说的是,我有这个Add Recipe按钮。如果我点击这个按钮,AddRecipe表单显示出来。 –

+0

[... this.state.recipes,recipe] === this.state.recipes.concat([recipe]) Spread运算符只是提取数组或对象内的内容,并将其与提供的数据进行连接/分配。 由于将来使用shouldComponentUpdate函数,总是返回一个新变量而不是改变现有变量是一种好习惯。 –