React组件不显示

时间:2017-04-02 07:56:41

标签: reactjs jsx

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组件。

1 个答案:

答案 0 :(得分: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组件,并基于props设置className:

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