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组件。
我强烈建议你参考一些好教程。 – Ved
是的,我正在从Wes Bos教程中学习。 –